1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.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"
27 GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
29 //===----------------------------------------------------------------------===//
30 // DAGISelEmitter Helper methods
33 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
35 static bool NodeIsComplexPattern(TreePatternNode *N) {
36 return (N->isLeaf() &&
37 dynamic_cast<DefInit*>(N->getLeafValue()) &&
38 static_cast<DefInit*>(N->getLeafValue())->getDef()->
39 isSubClassOf("ComplexPattern"));
42 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
43 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
44 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
45 CodeGenDAGPatterns &CGP) {
47 dynamic_cast<DefInit*>(N->getLeafValue()) &&
48 static_cast<DefInit*>(N->getLeafValue())->getDef()->
49 isSubClassOf("ComplexPattern")) {
50 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
56 /// getPatternSize - Return the 'size' of this pattern. We want to match large
57 /// patterns before small ones. This is used to determine the size of a
59 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
60 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
61 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
62 P->getExtTypeNum(0) == MVT::isVoid ||
63 P->getExtTypeNum(0) == MVT::Flag ||
64 P->getExtTypeNum(0) == MVT::iPTR ||
65 P->getExtTypeNum(0) == MVT::iPTRAny) &&
66 "Not a valid pattern node to size!");
67 unsigned Size = 3; // The node itself.
68 // If the root node is a ConstantSDNode, increases its size.
69 // e.g. (set R32:$dst, 0).
70 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
73 // FIXME: This is a hack to statically increase the priority of patterns
74 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
75 // Later we can allow complexity / cost for each pattern to be (optionally)
76 // specified. To get best possible pattern match we'll need to dynamically
77 // calculate the complexity of all patterns a dag can potentially map to.
78 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
80 Size += AM->getNumOperands() * 3;
82 // If this node has some predicate function that must match, it adds to the
83 // complexity of this node.
84 if (!P->getPredicateFns().empty())
87 // Count children in the count if they are also nodes.
88 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
89 TreePatternNode *Child = P->getChild(i);
90 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
91 Size += getPatternSize(Child, CGP);
92 else if (Child->isLeaf()) {
93 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
94 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
95 else if (NodeIsComplexPattern(Child))
96 Size += getPatternSize(Child, CGP);
97 else if (!Child->getPredicateFns().empty())
105 /// getResultPatternCost - Compute the number of instructions for this pattern.
106 /// This is a temporary hack. We should really include the instruction
107 /// latencies in this calculation.
108 static unsigned getResultPatternCost(TreePatternNode *P,
109 CodeGenDAGPatterns &CGP) {
110 if (P->isLeaf()) return 0;
113 Record *Op = P->getOperator();
114 if (Op->isSubClassOf("Instruction")) {
116 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
117 if (II.usesCustomInserter)
120 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
121 Cost += getResultPatternCost(P->getChild(i), CGP);
125 /// getResultPatternCodeSize - Compute the code size of instructions for this
127 static unsigned getResultPatternSize(TreePatternNode *P,
128 CodeGenDAGPatterns &CGP) {
129 if (P->isLeaf()) return 0;
132 Record *Op = P->getOperator();
133 if (Op->isSubClassOf("Instruction")) {
134 Cost += Op->getValueAsInt("CodeSize");
136 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
137 Cost += getResultPatternSize(P->getChild(i), CGP);
141 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
142 // In particular, we want to match maximal patterns first and lowest cost within
143 // a particular complexity first.
144 struct PatternSortingPredicate {
145 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
146 CodeGenDAGPatterns &CGP;
148 typedef std::pair<unsigned, std::string> CodeLine;
149 typedef std::vector<CodeLine> CodeList;
150 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
152 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
153 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
154 const PatternToMatch *LHS = LHSPair.first;
155 const PatternToMatch *RHS = RHSPair.first;
157 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
158 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
159 LHSSize += LHS->getAddedComplexity();
160 RHSSize += RHS->getAddedComplexity();
161 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
162 if (LHSSize < RHSSize) return false;
164 // If the patterns have equal complexity, compare generated instruction cost
165 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
166 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
167 if (LHSCost < RHSCost) return true;
168 if (LHSCost > RHSCost) return false;
170 return getResultPatternSize(LHS->getDstPattern(), CGP) <
171 getResultPatternSize(RHS->getDstPattern(), CGP);
175 /// getRegisterValueType - Look up and return the ValueType of the specified
176 /// register. If the register is a member of multiple register classes which
177 /// have different associated types, return MVT::Other.
178 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
179 bool FoundRC = false;
180 MVT::SimpleValueType VT = MVT::Other;
181 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
182 std::vector<CodeGenRegisterClass>::const_iterator RC;
183 std::vector<Record*>::const_iterator Element;
185 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
186 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
187 if (Element != (*RC).Elements.end()) {
190 VT = (*RC).getValueTypeNum(0);
193 if (VT != (*RC).getValueTypeNum(0)) {
194 // Types of the RC's do not agree. Return MVT::Other. The
195 // target is responsible for handling this.
205 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
206 /// type information from it.
207 static void RemoveAllTypes(TreePatternNode *N) {
210 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
211 RemoveAllTypes(N->getChild(i));
214 /// NodeHasProperty - return true if TreePatternNode has the specified
216 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
217 CodeGenDAGPatterns &CGP) {
219 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
221 return CP->hasProperty(Property);
224 Record *Operator = N->getOperator();
225 if (!Operator->isSubClassOf("SDNode")) return false;
227 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
230 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
231 CodeGenDAGPatterns &CGP) {
232 if (NodeHasProperty(N, Property, CGP))
235 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
236 TreePatternNode *Child = N->getChild(i);
237 if (PatternHasProperty(Child, Property, CGP))
244 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
245 return CGP.getSDNodeInfo(Op).getEnumName();
249 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
250 bool isStore = !N->isLeaf() &&
251 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
252 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
255 bool HasChain = false;
256 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
257 TreePatternNode *Child = N->getChild(i);
258 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
266 //===----------------------------------------------------------------------===//
267 // Node Transformation emitter implementation.
269 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
270 // Walk the pattern fragments, adding them to a map, which sorts them by
272 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
273 NXsByNameTy NXsByName;
275 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
277 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
279 OS << "\n// Node transformations.\n";
281 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
283 Record *SDNode = I->second.first;
284 std::string Code = I->second.second;
286 if (Code.empty()) continue; // Empty code? Skip it.
288 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
289 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
291 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
293 if (ClassName != "SDNode")
294 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
295 OS << Code << "\n}\n";
299 //===----------------------------------------------------------------------===//
300 // Predicate emitter implementation.
303 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
304 OS << "\n// Predicate functions.\n";
306 // Walk the pattern fragments, adding them to a map, which sorts them by
308 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
309 PFsByNameTy PFsByName;
311 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
313 PFsByName.insert(std::make_pair(I->first->getName(), *I));
316 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
318 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
319 TreePattern *P = I->second.second;
321 // If there is a code init for this fragment, emit the predicate code.
322 std::string Code = PatFragRecord->getValueAsCode("Predicate");
323 if (Code.empty()) continue;
325 if (P->getOnlyTree()->isLeaf())
326 OS << "inline bool Predicate_" << PatFragRecord->getName()
327 << "(SDNode *N) {\n";
329 std::string ClassName =
330 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
331 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
333 OS << "inline bool Predicate_" << PatFragRecord->getName()
334 << "(SDNode *" << C2 << ") {\n";
335 if (ClassName != "SDNode")
336 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
338 OS << Code << "\n}\n";
345 //===----------------------------------------------------------------------===//
346 // PatternCodeEmitter implementation.
348 class PatternCodeEmitter {
350 CodeGenDAGPatterns &CGP;
353 std::string PredicateCheck;
356 // Instruction selector pattern.
357 TreePatternNode *Pattern;
358 // Matched instruction.
359 TreePatternNode *Instruction;
361 // Node to name mapping
362 std::map<std::string, std::string> VariableMap;
363 // Node to operator mapping
364 std::map<std::string, Record*> OperatorMap;
365 // Name of the folded node which produces a flag.
366 std::pair<std::string, unsigned> FoldedFlag;
367 // Names of all the folded nodes which produce chains.
368 std::vector<std::pair<std::string, unsigned> > FoldedChains;
369 // Original input chain(s).
370 std::vector<std::pair<std::string, std::string> > OrigChains;
371 std::set<std::string> Duplicates;
373 /// LSI - Load/Store information.
374 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
375 /// for each memory access. This facilitates the use of AliasAnalysis in
377 std::vector<std::string> LSI;
379 /// GeneratedCode - This is the buffer that we emit code to. The first int
380 /// indicates whether this is an exit predicate (something that should be
381 /// tested, and if true, the match fails) [when 1], or normal code to emit
382 /// [when 0], or initialization code to emit [when 2].
383 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
384 /// GeneratedDecl - This is the set of all SDValue declarations needed for
385 /// the set of patterns for each top-level opcode.
386 std::set<std::string> &GeneratedDecl;
387 /// TargetOpcodes - The target specific opcodes used by the resulting
389 std::vector<std::string> &TargetOpcodes;
390 std::vector<std::string> &TargetVTs;
391 /// OutputIsVariadic - Records whether the instruction output pattern uses
392 /// variable_ops. This requires that the Emit function be passed an
393 /// additional argument to indicate where the input varargs operands
395 bool &OutputIsVariadic;
396 /// NumInputRootOps - Records the number of operands the root node of the
397 /// input pattern has. This information is used in the generated code to
398 /// pass to Emit functions when variable_ops processing is needed.
399 unsigned &NumInputRootOps;
401 std::string ChainName;
406 void emitCheck(const std::string &S) {
408 GeneratedCode.push_back(std::make_pair(1, S));
410 void emitCode(const std::string &S) {
412 GeneratedCode.push_back(std::make_pair(0, S));
414 void emitInit(const std::string &S) {
416 GeneratedCode.push_back(std::make_pair(2, S));
418 void emitDecl(const std::string &S) {
419 assert(!S.empty() && "Invalid declaration");
420 GeneratedDecl.insert(S);
422 void emitOpcode(const std::string &Opc) {
423 TargetOpcodes.push_back(Opc);
426 void emitVT(const std::string &VT) {
427 TargetVTs.push_back(VT);
431 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
432 TreePatternNode *pattern, TreePatternNode *instr,
433 std::vector<std::pair<unsigned, std::string> > &gc,
434 std::set<std::string> &gd,
435 std::vector<std::string> &to,
436 std::vector<std::string> &tv,
439 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
440 GeneratedCode(gc), GeneratedDecl(gd),
441 TargetOpcodes(to), TargetVTs(tv),
442 OutputIsVariadic(oiv), NumInputRootOps(niro),
443 TmpNo(0), OpcNo(0), VTNo(0) {}
445 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
446 /// if the match fails. At this point, we already know that the opcode for N
447 /// matches, and the SDNode for the result has the RootName specified name.
448 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
449 const std::string &RootName, const std::string &ChainSuffix,
452 // Save loads/stores matched by a pattern.
453 if (!N->isLeaf() && N->getName().empty()) {
454 if (NodeHasProperty(N, SDNPMemOperand, CGP))
455 LSI.push_back(RootName);
458 bool isRoot = (P == NULL);
459 // Emit instruction predicates. Each predicate is just a string for now.
461 // Record input varargs info.
462 NumInputRootOps = N->getNumChildren();
464 if (DisablePatternForFastISel(N, CGP))
465 emitCheck("OptLevel != CodeGenOpt::None");
467 emitCheck(PredicateCheck);
471 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
472 emitCheck("cast<ConstantSDNode>(" + RootName +
473 ")->getSExtValue() == INT64_C(" +
474 itostr(II->getValue()) + ")");
476 } else if (!NodeIsComplexPattern(N)) {
477 assert(0 && "Cannot match this as a leaf value!");
482 // If this node has a name associated with it, capture it in VariableMap. If
483 // we already saw this in the pattern, emit code to verify dagness.
484 if (!N->getName().empty()) {
485 std::string &VarMapEntry = VariableMap[N->getName()];
486 if (VarMapEntry.empty()) {
487 VarMapEntry = RootName;
489 // If we get here, this is a second reference to a specific name. Since
490 // we already have checked that the first reference is valid, we don't
491 // have to recursively match it, just check that it's the same as the
492 // previously named thing.
493 emitCheck(VarMapEntry + " == " + RootName);
498 OperatorMap[N->getName()] = N->getOperator();
502 // Emit code to load the child nodes and match their contents recursively.
504 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
505 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
506 bool EmittedUseCheck = false;
511 // Multiple uses of actual result?
512 emitCheck(RootName + ".hasOneUse()");
513 EmittedUseCheck = true;
515 // If the immediate use can somehow reach this node through another
516 // path, then can't fold it either or it will create a cycle.
517 // e.g. In the following diagram, XX can reach ld through YY. If
518 // ld is folded into XX, then YY is both a predecessor and a successor
528 bool NeedCheck = P != Pattern;
530 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
532 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
533 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
534 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
535 PInfo.getNumOperands() > 1 ||
536 PInfo.hasProperty(SDNPHasChain) ||
537 PInfo.hasProperty(SDNPInFlag) ||
538 PInfo.hasProperty(SDNPOptInFlag);
542 std::string ParentName(RootName.begin(), RootName.end()-1);
543 emitCheck("IsLegalAndProfitableToFold(" + RootName +
544 ".getNode(), " + ParentName + ".getNode(), N.getNode())");
551 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
552 "IsChainCompatible(" + ChainName + ".getNode(), " +
553 RootName + ".getNode()))");
554 OrigChains.push_back(std::make_pair(ChainName, RootName));
557 ChainName = "Chain" + ChainSuffix;
558 emitInit("SDValue " + ChainName + " = " + RootName +
563 // Don't fold any node which reads or writes a flag and has multiple uses.
564 // FIXME: We really need to separate the concepts of flag and "glue". Those
565 // real flag results, e.g. X86CMP output, can have multiple uses.
566 // FIXME: If the optional incoming flag does not exist. Then it is ok to
569 (PatternHasProperty(N, SDNPInFlag, CGP) ||
570 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
571 PatternHasProperty(N, SDNPOutFlag, CGP))) {
572 if (!EmittedUseCheck) {
573 // Multiple uses of actual result?
574 emitCheck(RootName + ".hasOneUse()");
578 // If there are node predicates for this, emit the calls.
579 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
580 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
582 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
583 // a constant without a predicate fn that has more that one bit set, handle
584 // this as a special case. This is usually for targets that have special
585 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
586 // handling stuff). Using these instructions is often far more efficient
587 // than materializing the constant. Unfortunately, both the instcombiner
588 // and the dag combiner can often infer that bits are dead, and thus drop
589 // them from the mask in the dag. For example, it might turn 'AND X, 255'
590 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
593 (N->getOperator()->getName() == "and" ||
594 N->getOperator()->getName() == "or") &&
595 N->getChild(1)->isLeaf() &&
596 N->getChild(1)->getPredicateFns().empty()) {
597 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
598 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
599 emitInit("SDValue " + RootName + "0" + " = " +
600 RootName + ".getOperand(" + utostr(0) + ");");
601 emitInit("SDValue " + RootName + "1" + " = " +
602 RootName + ".getOperand(" + utostr(1) + ");");
604 unsigned NTmp = TmpNo++;
605 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
606 " = dyn_cast<ConstantSDNode>(" + RootName + "1);");
607 emitCheck("Tmp" + utostr(NTmp));
608 const char *MaskPredicate = N->getOperator()->getName() == "or"
609 ? "CheckOrMask(" : "CheckAndMask(";
610 emitCheck(MaskPredicate + RootName + "0, Tmp" + utostr(NTmp) +
611 ", INT64_C(" + itostr(II->getValue()) + "))");
613 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
614 ChainSuffix + utostr(0), FoundChain);
620 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
621 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
622 RootName + ".getOperand(" +utostr(OpNo) + ");");
624 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
625 ChainSuffix + utostr(OpNo), FoundChain);
628 // Handle cases when root is a complex pattern.
629 const ComplexPattern *CP;
630 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
631 std::string Fn = CP->getSelectFunc();
632 unsigned NumOps = CP->getNumOperands();
633 for (unsigned i = 0; i < NumOps; ++i) {
634 emitDecl("CPTmp" + RootName + "_" + utostr(i));
635 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
637 if (CP->hasProperty(SDNPHasChain)) {
638 emitDecl("CPInChain");
639 emitDecl("Chain" + ChainSuffix);
640 emitCode("SDValue CPInChain;");
641 emitCode("SDValue Chain" + ChainSuffix + ";");
644 std::string Code = Fn + "(" + RootName + ", " + RootName;
645 for (unsigned i = 0; i < NumOps; i++)
646 Code += ", CPTmp" + RootName + "_" + utostr(i);
647 if (CP->hasProperty(SDNPHasChain)) {
648 ChainName = "Chain" + ChainSuffix;
649 Code += ", CPInChain, Chain" + ChainSuffix;
651 emitCheck(Code + ")");
655 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
656 const std::string &RootName,
657 const std::string &ChainSuffix, bool &FoundChain) {
658 if (!Child->isLeaf()) {
659 // If it's not a leaf, recursively match.
660 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
661 emitCheck(RootName + ".getOpcode() == " +
662 CInfo.getEnumName());
663 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
664 bool HasChain = false;
665 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
667 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
669 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
670 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
671 "Pattern folded multiple nodes which produce flags?");
672 FoldedFlag = std::make_pair(RootName,
673 CInfo.getNumResults() + (unsigned)HasChain);
676 // If this child has a name associated with it, capture it in VarMap. If
677 // we already saw this in the pattern, emit code to verify dagness.
678 if (!Child->getName().empty()) {
679 std::string &VarMapEntry = VariableMap[Child->getName()];
680 if (VarMapEntry.empty()) {
681 VarMapEntry = RootName;
683 // If we get here, this is a second reference to a specific name.
684 // Since we already have checked that the first reference is valid,
685 // we don't have to recursively match it, just check that it's the
686 // same as the previously named thing.
687 emitCheck(VarMapEntry + " == " + RootName);
688 Duplicates.insert(RootName);
693 // Handle leaves of various types.
694 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
695 Record *LeafRec = DI->getDef();
696 if (LeafRec->isSubClassOf("RegisterClass") ||
697 LeafRec->isSubClassOf("PointerLikeRegClass")) {
698 // Handle register references. Nothing to do here.
699 } else if (LeafRec->isSubClassOf("Register")) {
700 // Handle register references.
701 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
702 // Handle complex pattern.
703 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
704 std::string Fn = CP->getSelectFunc();
705 unsigned NumOps = CP->getNumOperands();
706 for (unsigned i = 0; i < NumOps; ++i) {
707 emitDecl("CPTmp" + RootName + "_" + utostr(i));
708 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
710 if (CP->hasProperty(SDNPHasChain)) {
711 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
712 FoldedChains.push_back(std::make_pair("CPInChain",
713 PInfo.getNumResults()));
714 ChainName = "Chain" + ChainSuffix;
715 emitDecl("CPInChain");
717 emitCode("SDValue CPInChain;");
718 emitCode("SDValue " + ChainName + ";");
721 std::string Code = Fn + "(N, ";
722 if (CP->hasProperty(SDNPHasChain)) {
723 std::string ParentName(RootName.begin(), RootName.end()-1);
724 Code += ParentName + ", ";
727 for (unsigned i = 0; i < NumOps; i++)
728 Code += ", CPTmp" + RootName + "_" + utostr(i);
729 if (CP->hasProperty(SDNPHasChain))
730 Code += ", CPInChain, Chain" + ChainSuffix;
731 emitCheck(Code + ")");
732 } else if (LeafRec->getName() == "srcvalue") {
733 // Place holder for SRCVALUE nodes. Nothing to do here.
734 } else if (LeafRec->isSubClassOf("ValueType")) {
735 // Make sure this is the specified value type.
736 emitCheck("cast<VTSDNode>(" + RootName +
737 ")->getVT() == MVT::" + LeafRec->getName());
738 } else if (LeafRec->isSubClassOf("CondCode")) {
739 // Make sure this is the specified cond code.
740 emitCheck("cast<CondCodeSDNode>(" + RootName +
741 ")->get() == ISD::" + LeafRec->getName());
747 assert(0 && "Unknown leaf type!");
750 // If there are node predicates for this, emit the calls.
751 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
752 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
754 } else if (IntInit *II =
755 dynamic_cast<IntInit*>(Child->getLeafValue())) {
756 unsigned NTmp = TmpNo++;
757 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
758 " = dyn_cast<ConstantSDNode>("+
760 emitCheck("Tmp" + utostr(NTmp));
761 unsigned CTmp = TmpNo++;
762 emitCode("int64_t CN"+ utostr(CTmp) +
763 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
764 emitCheck("CN" + utostr(CTmp) + " == "
765 "INT64_C(" +itostr(II->getValue()) + ")");
770 assert(0 && "Unknown leaf type!");
775 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
776 /// we actually have to build a DAG!
777 std::vector<std::string>
778 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
779 bool InFlagDecled, bool ResNodeDecled,
780 bool LikeLeaf = false, bool isRoot = false) {
781 // List of arguments of getMachineNode() or SelectNodeTo().
782 std::vector<std::string> NodeOps;
783 // This is something selected from the pattern we matched.
784 if (!N->getName().empty()) {
785 const std::string &VarName = N->getName();
786 std::string Val = VariableMap[VarName];
787 bool ModifiedVal = false;
789 errs() << "Variable '" << VarName << " referenced but not defined "
790 << "and not caught earlier!\n";
793 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
794 // Already selected this operand, just return the tmpval.
795 NodeOps.push_back(Val);
799 const ComplexPattern *CP;
800 unsigned ResNo = TmpNo++;
801 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
802 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
803 std::string CastType;
804 std::string TmpVar = "Tmp" + utostr(ResNo);
805 switch (N->getTypeNum(0)) {
807 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
808 << " type as an immediate constant. Aborting\n";
810 case MVT::i1: CastType = "bool"; break;
811 case MVT::i8: CastType = "unsigned char"; break;
812 case MVT::i16: CastType = "unsigned short"; break;
813 case MVT::i32: CastType = "unsigned"; break;
814 case MVT::i64: CastType = "uint64_t"; break;
816 emitCode("SDValue " + TmpVar +
817 " = CurDAG->getTargetConstant(((" + CastType +
818 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
819 getEnumName(N->getTypeNum(0)) + ");");
820 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
821 // value if used multiple times by this pattern result.
824 NodeOps.push_back(Val);
825 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
826 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
827 std::string TmpVar = "Tmp" + utostr(ResNo);
828 emitCode("SDValue " + TmpVar +
829 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
830 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
831 Val + ")->getValueType(0));");
832 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
833 // value if used multiple times by this pattern result.
836 NodeOps.push_back(Val);
837 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
838 Record *Op = OperatorMap[N->getName()];
839 // Transform ExternalSymbol to TargetExternalSymbol
840 if (Op && Op->getName() == "externalsym") {
841 std::string TmpVar = "Tmp"+utostr(ResNo);
842 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
843 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
844 Val + ")->getSymbol(), " +
845 getEnumName(N->getTypeNum(0)) + ");");
846 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
847 // this value if used multiple times by this pattern result.
851 NodeOps.push_back(Val);
852 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
853 || N->getOperator()->getName() == "tglobaltlsaddr")) {
854 Record *Op = OperatorMap[N->getName()];
855 // Transform GlobalAddress to TargetGlobalAddress
856 if (Op && (Op->getName() == "globaladdr" ||
857 Op->getName() == "globaltlsaddr")) {
858 std::string TmpVar = "Tmp" + utostr(ResNo);
859 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
860 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
861 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
863 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
864 // this value if used multiple times by this pattern result.
868 NodeOps.push_back(Val);
869 } else if (!N->isLeaf()
870 && (N->getOperator()->getName() == "texternalsym"
871 || N->getOperator()->getName() == "tconstpool")) {
872 // Do not rewrite the variable name, since we don't generate a new
874 NodeOps.push_back(Val);
875 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
876 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
877 NodeOps.push_back("CPTmp" + Val + "_" + utostr(i));
880 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
881 // node even if it isn't one. Don't select it.
883 if (isRoot && N->isLeaf()) {
884 emitCode("ReplaceUses(N, " + Val + ");");
885 emitCode("return NULL;");
888 NodeOps.push_back(Val);
892 VariableMap[VarName] = Val;
897 // If this is an explicit register reference, handle it.
898 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
899 unsigned ResNo = TmpNo++;
900 if (DI->getDef()->isSubClassOf("Register")) {
901 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
902 getQualifiedName(DI->getDef()) + ", " +
903 getEnumName(N->getTypeNum(0)) + ");");
904 NodeOps.push_back("Tmp" + utostr(ResNo));
906 } else if (DI->getDef()->getName() == "zero_reg") {
907 emitCode("SDValue Tmp" + utostr(ResNo) +
908 " = CurDAG->getRegister(0, " +
909 getEnumName(N->getTypeNum(0)) + ");");
910 NodeOps.push_back("Tmp" + utostr(ResNo));
912 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
913 // Handle a reference to a register class. This is used
914 // in COPY_TO_SUBREG instructions.
915 emitCode("SDValue Tmp" + utostr(ResNo) +
916 " = CurDAG->getTargetConstant(" +
917 getQualifiedName(DI->getDef()) + "RegClassID, " +
919 NodeOps.push_back("Tmp" + utostr(ResNo));
922 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
923 unsigned ResNo = TmpNo++;
924 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
925 emitCode("SDValue Tmp" + utostr(ResNo) +
926 " = CurDAG->getTargetConstant(0x" +
927 utohexstr((uint64_t) II->getValue()) +
928 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
929 NodeOps.push_back("Tmp" + utostr(ResNo));
936 assert(0 && "Unknown leaf type!");
940 Record *Op = N->getOperator();
941 if (Op->isSubClassOf("Instruction")) {
942 const CodeGenTarget &CGT = CGP.getTargetInfo();
943 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
944 const DAGInstruction &Inst = CGP.getInstruction(Op);
945 const TreePattern *InstPat = Inst.getPattern();
946 // FIXME: Assume actual pattern comes before "implicit".
947 TreePatternNode *InstPatNode =
948 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
949 : (InstPat ? InstPat->getTree(0) : NULL);
950 if (InstPatNode && !InstPatNode->isLeaf() &&
951 InstPatNode->getOperator()->getName() == "set") {
952 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
954 bool IsVariadic = isRoot && II.isVariadic;
955 // FIXME: fix how we deal with physical register operands.
956 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
957 bool HasImpResults = isRoot && DstRegs.size() > 0;
958 bool NodeHasOptInFlag = isRoot &&
959 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
960 bool NodeHasInFlag = isRoot &&
961 PatternHasProperty(Pattern, SDNPInFlag, CGP);
962 bool NodeHasOutFlag = isRoot &&
963 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
964 bool NodeHasChain = InstPatNode &&
965 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
966 bool InputHasChain = isRoot &&
967 NodeHasProperty(Pattern, SDNPHasChain, CGP);
968 unsigned NumResults = Inst.getNumResults();
969 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
971 // Record output varargs info.
972 OutputIsVariadic = IsVariadic;
974 if (NodeHasOptInFlag) {
975 emitCode("bool HasInFlag = "
976 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
979 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
981 // How many results is this pattern expected to produce?
982 unsigned NumPatResults = 0;
983 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
984 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
985 if (VT != MVT::isVoid && VT != MVT::Flag)
989 if (OrigChains.size() > 0) {
990 // The original input chain is being ignored. If it is not just
991 // pointing to the op that's being folded, we should create a
992 // TokenFactor with it and the chain of the folded op as the new chain.
993 // We could potentially be doing multiple levels of folding, in that
994 // case, the TokenFactor can have more operands.
995 emitCode("SmallVector<SDValue, 8> InChains;");
996 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
997 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
998 OrigChains[i].second + ".getNode()) {");
999 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1002 emitCode("InChains.push_back(" + ChainName + ");");
1003 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1004 "N.getDebugLoc(), MVT::Other, "
1005 "&InChains[0], InChains.size());");
1007 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1008 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1012 // Loop over all of the operands of the instruction pattern, emitting code
1013 // to fill them all in. The node 'N' usually has number children equal to
1014 // the number of input operands of the instruction. However, in cases
1015 // where there are predicate operands for an instruction, we need to fill
1016 // in the 'execute always' values. Match up the node operands to the
1017 // instruction operands to do this.
1018 std::vector<std::string> AllOps;
1019 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1020 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1021 std::vector<std::string> Ops;
1023 // Determine what to emit for this operand.
1024 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1025 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1026 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1027 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1028 // This is a predicate or optional def operand; emit the
1029 // 'default ops' operands.
1030 const DAGDefaultOperand &DefaultOp =
1031 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1032 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1033 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1034 InFlagDecled, ResNodeDecled);
1035 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1038 // Otherwise this is a normal operand or a predicate operand without
1039 // 'execute always'; emit it.
1040 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1041 InFlagDecled, ResNodeDecled);
1042 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1047 // Emit all the chain and CopyToReg stuff.
1048 bool ChainEmitted = NodeHasChain;
1049 if (NodeHasInFlag || HasImpInputs)
1050 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1051 InFlagDecled, ResNodeDecled, true);
1052 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1053 if (!InFlagDecled) {
1054 emitCode("SDValue InFlag(0, 0);");
1055 InFlagDecled = true;
1057 if (NodeHasOptInFlag) {
1058 emitCode("if (HasInFlag) {");
1059 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1064 unsigned ResNo = TmpNo++;
1066 unsigned OpsNo = OpcNo;
1067 std::string CodePrefix;
1068 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1069 std::deque<std::string> After;
1070 std::string NodeName;
1072 NodeName = "Tmp" + utostr(ResNo);
1073 CodePrefix = "SDValue " + NodeName + "(";
1075 NodeName = "ResNode";
1076 if (!ResNodeDecled) {
1077 CodePrefix = "SDNode *" + NodeName + " = ";
1078 ResNodeDecled = true;
1080 CodePrefix = NodeName + " = ";
1083 std::string Code = "Opc" + utostr(OpcNo);
1085 if (!isRoot || (InputHasChain && !NodeHasChain))
1086 // For call to "getMachineNode()".
1087 Code += ", N.getDebugLoc()";
1089 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1091 // Output order: results, chain, flags
1093 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1094 Code += ", VT" + utostr(VTNo);
1095 emitVT(getEnumName(N->getTypeNum(0)));
1097 // Add types for implicit results in physical registers, scheduler will
1098 // care of adding copyfromreg nodes.
1099 for (unsigned i = 0; i < NumDstRegs; i++) {
1100 Record *RR = DstRegs[i];
1101 if (RR->isSubClassOf("Register")) {
1102 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1103 Code += ", " + getEnumName(RVT);
1107 Code += ", MVT::Other";
1109 Code += ", MVT::Flag";
1113 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1114 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1117 // Figure out whether any operands at the end of the op list are not
1118 // part of the variable section.
1119 std::string EndAdjust;
1120 if (NodeHasInFlag || HasImpInputs)
1121 EndAdjust = "-1"; // Always has one flag.
1122 else if (NodeHasOptInFlag)
1123 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1125 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1126 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1128 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1132 // Populate MemRefs with entries for each memory accesses covered by
1134 if (isRoot && !LSI.empty()) {
1135 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1136 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1137 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1138 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1139 emitCode(MemRefs + "[" + utostr(i) + "] = "
1140 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1141 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1142 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1148 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1150 AllOps.push_back(ChainName);
1154 if (NodeHasInFlag || HasImpInputs)
1155 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1156 else if (NodeHasOptInFlag) {
1157 emitCode("if (HasInFlag)");
1158 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1160 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1162 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1163 AllOps.push_back("InFlag");
1165 unsigned NumOps = AllOps.size();
1167 if (!NodeHasOptInFlag && NumOps < 4) {
1168 for (unsigned i = 0; i != NumOps; ++i)
1169 Code += ", " + AllOps[i];
1171 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1172 for (unsigned i = 0; i != NumOps; ++i) {
1173 OpsCode += AllOps[i];
1177 emitCode(OpsCode + " };");
1178 Code += ", Ops" + utostr(OpsNo) + ", ";
1179 if (NodeHasOptInFlag) {
1180 Code += "HasInFlag ? ";
1181 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1183 Code += utostr(NumOps);
1190 std::vector<std::string> ReplaceFroms;
1191 std::vector<std::string> ReplaceTos;
1193 NodeOps.push_back("Tmp" + utostr(ResNo));
1196 if (NodeHasOutFlag) {
1197 if (!InFlagDecled) {
1198 After.push_back("SDValue InFlag(ResNode, " +
1199 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1201 InFlagDecled = true;
1203 After.push_back("InFlag = SDValue(ResNode, " +
1204 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1208 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1209 ReplaceFroms.push_back("SDValue(" +
1210 FoldedChains[j].first + ".getNode(), " +
1211 utostr(FoldedChains[j].second) +
1213 ReplaceTos.push_back("SDValue(ResNode, " +
1214 utostr(NumResults+NumDstRegs) + ")");
1217 if (NodeHasOutFlag) {
1218 if (FoldedFlag.first != "") {
1219 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1220 utostr(FoldedFlag.second) + ")");
1221 ReplaceTos.push_back("InFlag");
1223 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1224 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1225 utostr(NumPatResults + (unsigned)InputHasChain)
1227 ReplaceTos.push_back("InFlag");
1231 if (!ReplaceFroms.empty() && InputHasChain) {
1232 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1233 utostr(NumPatResults) + ")");
1234 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1235 ChainName + ".getResNo()" + ")");
1236 ChainAssignmentNeeded |= NodeHasChain;
1239 // User does not expect the instruction would produce a chain!
1240 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1242 } else if (InputHasChain && !NodeHasChain) {
1243 // One of the inner node produces a chain.
1244 if (NodeHasOutFlag) {
1245 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1246 utostr(NumPatResults+1) +
1248 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1250 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1251 utostr(NumPatResults) + ")");
1252 ReplaceTos.push_back(ChainName);
1256 if (ChainAssignmentNeeded) {
1257 // Remember which op produces the chain.
1258 std::string ChainAssign;
1260 ChainAssign = ChainName + " = SDValue(" + NodeName +
1261 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1263 ChainAssign = ChainName + " = SDValue(" + NodeName +
1264 ", " + utostr(NumResults+NumDstRegs) + ");";
1266 After.push_front(ChainAssign);
1269 if (ReplaceFroms.size() == 1) {
1270 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1271 ReplaceTos[0] + ");");
1272 } else if (!ReplaceFroms.empty()) {
1273 After.push_back("const SDValue Froms[] = {");
1274 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1275 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1276 After.push_back("};");
1277 After.push_back("const SDValue Tos[] = {");
1278 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1279 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1280 After.push_back("};");
1281 After.push_back("ReplaceUses(Froms, Tos, " +
1282 itostr(ReplaceFroms.size()) + ");");
1285 // We prefer to use SelectNodeTo since it avoids allocation when
1286 // possible and it avoids CSE map recalculation for the node's
1287 // users, however it's tricky to use in a non-root context.
1289 // We also don't use SelectNodeTo if the pattern replacement is being
1290 // used to jettison a chain result, since morphing the node in place
1291 // would leave users of the chain dangling.
1293 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1294 Code = "CurDAG->getMachineNode(" + Code;
1296 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1300 CodePrefix = "return ";
1302 After.push_back("return ResNode;");
1305 emitCode(CodePrefix + Code + ");");
1309 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1310 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1313 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1314 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1318 for (unsigned i = 0, e = After.size(); i != e; ++i)
1323 if (Op->isSubClassOf("SDNodeXForm")) {
1324 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1325 // PatLeaf node - the operand may or may not be a leaf node. But it should
1327 std::vector<std::string> Ops =
1328 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1329 ResNodeDecled, true);
1330 unsigned ResNo = TmpNo++;
1331 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1332 + "(" + Ops.back() + ".getNode());");
1333 NodeOps.push_back("Tmp" + utostr(ResNo));
1335 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1341 throw std::string("Unknown node in result pattern!");
1344 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1345 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1346 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1347 /// for, this returns true otherwise false if Pat has all types.
1348 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1349 const std::string &Prefix, bool isRoot = false) {
1351 if (Pat->getExtTypes() != Other->getExtTypes()) {
1352 // Move a type over from 'other' to 'pat'.
1353 Pat->setTypes(Other->getExtTypes());
1354 // The top level node type is checked outside of the select function.
1356 emitCheck(Prefix + ".getValueType() == " +
1357 getName(Pat->getTypeNum(0)));
1362 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1363 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1364 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1365 Prefix + utostr(OpNo)))
1371 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1373 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1374 bool &ChainEmitted, bool &InFlagDecled,
1375 bool &ResNodeDecled, bool isRoot = false) {
1376 const CodeGenTarget &T = CGP.getTargetInfo();
1378 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1379 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1380 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1381 TreePatternNode *Child = N->getChild(i);
1382 if (!Child->isLeaf()) {
1383 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1384 InFlagDecled, ResNodeDecled);
1386 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1387 if (!Child->getName().empty()) {
1388 std::string Name = RootName + utostr(OpNo);
1389 if (Duplicates.find(Name) != Duplicates.end())
1390 // A duplicate! Do not emit a copy for this node.
1394 Record *RR = DI->getDef();
1395 if (RR->isSubClassOf("Register")) {
1396 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1397 if (RVT == MVT::Flag) {
1398 if (!InFlagDecled) {
1399 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1400 InFlagDecled = true;
1402 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1404 if (!ChainEmitted) {
1405 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1406 ChainName = "Chain";
1407 ChainEmitted = true;
1409 if (!InFlagDecled) {
1410 emitCode("SDValue InFlag(0, 0);");
1411 InFlagDecled = true;
1413 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1414 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1415 ", " + RootName + ".getDebugLoc()" +
1416 ", " + getQualifiedName(RR) +
1417 ", " + RootName + utostr(OpNo) + ", InFlag).getNode();");
1418 ResNodeDecled = true;
1419 emitCode(ChainName + " = SDValue(ResNode, 0);");
1420 emitCode("InFlag = SDValue(ResNode, 1);");
1428 if (!InFlagDecled) {
1429 emitCode("SDValue InFlag = " + RootName +
1430 ".getOperand(" + utostr(OpNo) + ");");
1431 InFlagDecled = true;
1433 emitCode("InFlag = " + RootName +
1434 ".getOperand(" + utostr(OpNo) + ");");
1439 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1440 /// stream to match the pattern, and generate the code for the match if it
1441 /// succeeds. Returns true if the pattern is not guaranteed to match.
1442 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1443 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1444 std::set<std::string> &GeneratedDecl,
1445 std::vector<std::string> &TargetOpcodes,
1446 std::vector<std::string> &TargetVTs,
1447 bool &OutputIsVariadic,
1448 unsigned &NumInputRootOps) {
1449 OutputIsVariadic = false;
1450 NumInputRootOps = 0;
1452 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1453 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1454 GeneratedCode, GeneratedDecl,
1455 TargetOpcodes, TargetVTs,
1456 OutputIsVariadic, NumInputRootOps);
1458 // Emit the matcher, capturing named arguments in VariableMap.
1459 bool FoundChain = false;
1460 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1462 // TP - Get *SOME* tree pattern, we don't care which.
1463 TreePattern &TP = *CGP.pf_begin()->second;
1465 // At this point, we know that we structurally match the pattern, but the
1466 // types of the nodes may not match. Figure out the fewest number of type
1467 // comparisons we need to emit. For example, if there is only one integer
1468 // type supported by a target, there should be no type comparisons at all for
1469 // integer patterns!
1471 // To figure out the fewest number of type checks needed, clone the pattern,
1472 // remove the types, then perform type inference on the pattern as a whole.
1473 // If there are unresolved types, emit an explicit check for those types,
1474 // apply the type to the tree, then rerun type inference. Iterate until all
1475 // types are resolved.
1477 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1478 RemoveAllTypes(Pat);
1481 // Resolve/propagate as many types as possible.
1483 bool MadeChange = true;
1485 MadeChange = Pat->ApplyTypeConstraints(TP,
1486 true/*Ignore reg constraints*/);
1488 assert(0 && "Error: could not find consistent types for something we"
1489 " already decided was ok!");
1493 // Insert a check for an unresolved type and add it to the tree. If we find
1494 // an unresolved type to add a check for, this returns true and we iterate,
1495 // otherwise we are done.
1496 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1498 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1499 false, false, false, true);
1503 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1504 /// a line causes any of them to be empty, remove them and return true when
1506 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1507 std::vector<std::pair<unsigned, std::string> > > >
1509 bool ErasedPatterns = false;
1510 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1511 Patterns[i].second.pop_back();
1512 if (Patterns[i].second.empty()) {
1513 Patterns.erase(Patterns.begin()+i);
1515 ErasedPatterns = true;
1518 return ErasedPatterns;
1521 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1522 /// code together between the patterns.
1523 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1524 std::vector<std::pair<unsigned, std::string> > > >
1525 &Patterns, unsigned Indent,
1527 typedef std::pair<unsigned, std::string> CodeLine;
1528 typedef std::vector<CodeLine> CodeList;
1529 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1531 if (Patterns.empty()) return;
1533 // Figure out how many patterns share the next code line. Explicitly copy
1534 // FirstCodeLine so that we don't invalidate a reference when changing
1536 const CodeLine FirstCodeLine = Patterns.back().second.back();
1537 unsigned LastMatch = Patterns.size()-1;
1538 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1541 // If not all patterns share this line, split the list into two pieces. The
1542 // first chunk will use this line, the second chunk won't.
1543 if (LastMatch != 0) {
1544 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1545 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1547 // FIXME: Emit braces?
1548 if (Shared.size() == 1) {
1549 const PatternToMatch &Pattern = *Shared.back().first;
1550 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1551 Pattern.getSrcPattern()->print(OS);
1552 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1553 Pattern.getDstPattern()->print(OS);
1555 unsigned AddedComplexity = Pattern.getAddedComplexity();
1556 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1557 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1559 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1561 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1563 if (FirstCodeLine.first != 1) {
1564 OS << std::string(Indent, ' ') << "{\n";
1567 EmitPatterns(Shared, Indent, OS);
1568 if (FirstCodeLine.first != 1) {
1570 OS << std::string(Indent, ' ') << "}\n";
1573 if (Other.size() == 1) {
1574 const PatternToMatch &Pattern = *Other.back().first;
1575 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1576 Pattern.getSrcPattern()->print(OS);
1577 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1578 Pattern.getDstPattern()->print(OS);
1580 unsigned AddedComplexity = Pattern.getAddedComplexity();
1581 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1582 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1584 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1586 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1588 EmitPatterns(Other, Indent, OS);
1592 // Remove this code from all of the patterns that share it.
1593 bool ErasedPatterns = EraseCodeLine(Patterns);
1595 bool isPredicate = FirstCodeLine.first == 1;
1597 // Otherwise, every pattern in the list has this line. Emit it.
1600 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1602 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1604 // If the next code line is another predicate, and if all of the pattern
1605 // in this group share the same next line, emit it inline now. Do this
1606 // until we run out of common predicates.
1607 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1608 // Check that all of the patterns in Patterns end with the same predicate.
1609 bool AllEndWithSamePredicate = true;
1610 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1611 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1612 AllEndWithSamePredicate = false;
1615 // If all of the predicates aren't the same, we can't share them.
1616 if (!AllEndWithSamePredicate) break;
1618 // Otherwise we can. Emit it shared now.
1619 OS << " &&\n" << std::string(Indent+4, ' ')
1620 << Patterns.back().second.back().second;
1621 ErasedPatterns = EraseCodeLine(Patterns);
1628 EmitPatterns(Patterns, Indent, OS);
1631 OS << std::string(Indent-2, ' ') << "}\n";
1634 static std::string getLegalCName(std::string OpName) {
1635 std::string::size_type pos = OpName.find("::");
1636 if (pos != std::string::npos)
1637 OpName.replace(pos, 2, "_");
1641 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1642 const CodeGenTarget &Target = CGP.getTargetInfo();
1644 // Get the namespace to insert instructions into.
1645 std::string InstNS = Target.getInstNamespace();
1646 if (!InstNS.empty()) InstNS += "::";
1648 // Group the patterns by their top-level opcodes.
1649 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1650 // All unique target node emission functions.
1651 std::map<std::string, unsigned> EmitFunctions;
1652 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1653 E = CGP.ptm_end(); I != E; ++I) {
1654 const PatternToMatch &Pattern = *I;
1656 TreePatternNode *Node = Pattern.getSrcPattern();
1657 if (!Node->isLeaf()) {
1658 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1659 push_back(&Pattern);
1661 const ComplexPattern *CP;
1662 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1663 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1664 push_back(&Pattern);
1665 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1666 std::vector<Record*> OpNodes = CP->getRootNodes();
1667 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1668 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1669 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1673 errs() << "Unrecognized opcode '";
1675 errs() << "' on tree pattern '";
1676 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1682 // For each opcode, there might be multiple select functions, one per
1683 // ValueType of the node (or its first operand if it doesn't produce a
1684 // non-chain result.
1685 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1687 // Emit one Select_* method for each top-level opcode. We do this instead of
1688 // emitting one giant switch statement to support compilers where this will
1689 // result in the recursive functions taking less stack space.
1690 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1691 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1692 PBOI != E; ++PBOI) {
1693 const std::string &OpName = PBOI->first;
1694 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1695 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1697 // Split them into groups by type.
1698 std::map<MVT::SimpleValueType,
1699 std::vector<const PatternToMatch*> > PatternsByType;
1700 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1701 const PatternToMatch *Pat = PatternsOfOp[i];
1702 TreePatternNode *SrcPat = Pat->getSrcPattern();
1703 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1706 for (std::map<MVT::SimpleValueType,
1707 std::vector<const PatternToMatch*> >::iterator
1708 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1710 MVT::SimpleValueType OpVT = II->first;
1711 std::vector<const PatternToMatch*> &Patterns = II->second;
1712 typedef std::pair<unsigned, std::string> CodeLine;
1713 typedef std::vector<CodeLine> CodeList;
1714 typedef CodeList::iterator CodeListI;
1716 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1717 std::vector<std::vector<std::string> > PatternOpcodes;
1718 std::vector<std::vector<std::string> > PatternVTs;
1719 std::vector<std::set<std::string> > PatternDecls;
1720 std::vector<bool> OutputIsVariadicFlags;
1721 std::vector<unsigned> NumInputRootOpsCounts;
1722 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1723 CodeList GeneratedCode;
1724 std::set<std::string> GeneratedDecl;
1725 std::vector<std::string> TargetOpcodes;
1726 std::vector<std::string> TargetVTs;
1727 bool OutputIsVariadic;
1728 unsigned NumInputRootOps;
1729 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1730 TargetOpcodes, TargetVTs,
1731 OutputIsVariadic, NumInputRootOps);
1732 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1733 PatternDecls.push_back(GeneratedDecl);
1734 PatternOpcodes.push_back(TargetOpcodes);
1735 PatternVTs.push_back(TargetVTs);
1736 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1737 NumInputRootOpsCounts.push_back(NumInputRootOps);
1740 // Factor target node emission code (emitted by EmitResultCode) into
1741 // separate functions. Uniquing and share them among all instruction
1742 // selection routines.
1743 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1744 CodeList &GeneratedCode = CodeForPatterns[i].second;
1745 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1746 std::vector<std::string> &TargetVTs = PatternVTs[i];
1747 std::set<std::string> Decls = PatternDecls[i];
1748 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1749 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1750 std::vector<std::string> AddedInits;
1751 int CodeSize = (int)GeneratedCode.size();
1753 for (int j = CodeSize-1; j >= 0; --j) {
1754 if (LastPred == -1 && GeneratedCode[j].first == 1)
1756 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1757 AddedInits.push_back(GeneratedCode[j].second);
1760 std::string CalleeCode = "(const SDValue &N";
1761 std::string CallerCode = "(N";
1762 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1763 CalleeCode += ", unsigned Opc" + utostr(j);
1764 CallerCode += ", " + TargetOpcodes[j];
1766 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1767 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1768 CallerCode += ", " + TargetVTs[j];
1770 for (std::set<std::string>::iterator
1771 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1772 std::string Name = *I;
1773 CalleeCode += ", SDValue &" + Name;
1774 CallerCode += ", " + Name;
1777 if (OutputIsVariadic) {
1778 CalleeCode += ", unsigned NumInputRootOps";
1779 CallerCode += ", " + utostr(NumInputRootOps);
1783 CalleeCode += ") {\n";
1785 for (std::vector<std::string>::const_reverse_iterator
1786 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1787 CalleeCode += " " + *I + "\n";
1789 for (int j = LastPred+1; j < CodeSize; ++j)
1790 CalleeCode += " " + GeneratedCode[j].second + "\n";
1791 for (int j = LastPred+1; j < CodeSize; ++j)
1792 GeneratedCode.pop_back();
1793 CalleeCode += "}\n";
1795 // Uniquing the emission routines.
1796 unsigned EmitFuncNum;
1797 std::map<std::string, unsigned>::iterator EFI =
1798 EmitFunctions.find(CalleeCode);
1799 if (EFI != EmitFunctions.end()) {
1800 EmitFuncNum = EFI->second;
1802 EmitFuncNum = EmitFunctions.size();
1803 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1804 // Prevent emission routines from being inlined to reduce selection
1805 // routines stack frame sizes.
1806 OS << "DISABLE_INLINE ";
1807 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1810 // Replace the emission code within selection routines with calls to the
1811 // emission functions.
1813 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1815 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1816 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1818 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1819 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1820 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1821 GeneratedCode.push_back(std::make_pair(0, "}"));
1822 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1824 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1828 std::string OpVTStr;
1829 if (OpVT == MVT::iPTR) {
1831 } else if (OpVT == MVT::iPTRAny) {
1832 OpVTStr = "_iPTRAny";
1833 } else if (OpVT == MVT::isVoid) {
1834 // Nodes with a void result actually have a first result type of either
1835 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1836 // void to this case, we handle it specially here.
1838 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1840 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1841 OpcodeVTMap.find(OpName);
1842 if (OpVTI == OpcodeVTMap.end()) {
1843 std::vector<std::string> VTSet;
1844 VTSet.push_back(OpVTStr);
1845 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1847 OpVTI->second.push_back(OpVTStr);
1849 // We want to emit all of the matching code now. However, we want to emit
1850 // the matches in order of minimal cost. Sort the patterns so the least
1851 // cost one is at the start.
1852 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1853 PatternSortingPredicate(CGP));
1855 // Scan the code to see if all of the patterns are reachable and if it is
1856 // possible that the last one might not match.
1857 bool mightNotMatch = true;
1858 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1859 CodeList &GeneratedCode = CodeForPatterns[i].second;
1860 mightNotMatch = false;
1862 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1863 if (GeneratedCode[j].first == 1) { // predicate.
1864 mightNotMatch = true;
1869 // If this pattern definitely matches, and if it isn't the last one, the
1870 // patterns after it CANNOT ever match. Error out.
1871 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1872 errs() << "Pattern '";
1873 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1874 errs() << "' is impossible to select!\n";
1879 // Loop through and reverse all of the CodeList vectors, as we will be
1880 // accessing them from their logical front, but accessing the end of a
1881 // vector is more efficient.
1882 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1883 CodeList &GeneratedCode = CodeForPatterns[i].second;
1884 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1887 // Next, reverse the list of patterns itself for the same reason.
1888 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1890 OS << "SDNode *Select_" << getLegalCName(OpName)
1891 << OpVTStr << "(const SDValue &N) {\n";
1893 // Emit all of the patterns now, grouped together to share code.
1894 EmitPatterns(CodeForPatterns, 2, OS);
1896 // If the last pattern has predicates (which could fail) emit code to
1897 // catch the case where nothing handles a pattern.
1898 if (mightNotMatch) {
1900 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1901 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1902 OpName != "ISD::INTRINSIC_VOID")
1903 OS << " CannotYetSelect(N);\n";
1905 OS << " CannotYetSelectIntrinsic(N);\n";
1907 OS << " return NULL;\n";
1913 OS << "// The main instruction selector code.\n"
1914 << "SDNode *SelectCode(SDValue N) {\n"
1915 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT().SimpleTy;\n"
1916 << " switch (N.getOpcode()) {\n"
1918 << " assert(!N.isMachineOpcode() && \"Node already selected!\");\n"
1920 << " case ISD::EntryToken: // These nodes remain the same.\n"
1921 << " case ISD::BasicBlock:\n"
1922 << " case ISD::Register:\n"
1923 << " case ISD::HANDLENODE:\n"
1924 << " case ISD::TargetConstant:\n"
1925 << " case ISD::TargetConstantFP:\n"
1926 << " case ISD::TargetConstantPool:\n"
1927 << " case ISD::TargetFrameIndex:\n"
1928 << " case ISD::TargetExternalSymbol:\n"
1929 << " case ISD::TargetBlockAddress:\n"
1930 << " case ISD::TargetJumpTable:\n"
1931 << " case ISD::TargetGlobalTLSAddress:\n"
1932 << " case ISD::TargetGlobalAddress:\n"
1933 << " case ISD::TokenFactor:\n"
1934 << " case ISD::CopyFromReg:\n"
1935 << " case ISD::CopyToReg: {\n"
1936 << " return NULL;\n"
1938 << " case ISD::AssertSext:\n"
1939 << " case ISD::AssertZext: {\n"
1940 << " ReplaceUses(N, N.getOperand(0));\n"
1941 << " return NULL;\n"
1943 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1944 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1945 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1947 // Loop over all of the case statements, emiting a call to each method we
1949 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1950 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1951 PBOI != E; ++PBOI) {
1952 const std::string &OpName = PBOI->first;
1953 // Potentially multiple versions of select for this opcode. One for each
1954 // ValueType of the node (or its first true operand if it doesn't produce a
1956 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1957 OpcodeVTMap.find(OpName);
1958 std::vector<std::string> &OpVTs = OpVTI->second;
1959 OS << " case " << OpName << ": {\n";
1960 // If we have only one variant and it's the default, elide the
1961 // switch. Marginally faster, and makes MSVC happier.
1962 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1963 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1968 // Keep track of whether we see a pattern that has an iPtr result.
1969 bool HasPtrPattern = false;
1970 bool HasDefaultPattern = false;
1972 OS << " switch (NVT) {\n";
1973 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1974 std::string &VTStr = OpVTs[i];
1975 if (VTStr.empty()) {
1976 HasDefaultPattern = true;
1980 // If this is a match on iPTR: don't emit it directly, we need special
1982 if (VTStr == "_iPTR") {
1983 HasPtrPattern = true;
1986 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1987 << " return Select_" << getLegalCName(OpName)
1988 << VTStr << "(N);\n";
1990 OS << " default:\n";
1992 // If there is an iPTR result version of this pattern, emit it here.
1993 if (HasPtrPattern) {
1994 OS << " if (TLI.getPointerTy() == NVT)\n";
1995 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1997 if (HasDefaultPattern) {
1998 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2006 OS << " } // end of big switch.\n\n"
2007 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2008 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2009 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2010 << " CannotYetSelect(N);\n"
2012 << " CannotYetSelectIntrinsic(N);\n"
2014 << " return NULL;\n"
2018 void DAGISelEmitter::run(raw_ostream &OS) {
2019 EmitSourceFileHeader("DAG Instruction Selector for the " +
2020 CGP.getTargetInfo().getName() + " target", OS);
2022 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2023 << "// *** instruction selector class. These functions are really "
2026 OS << "// Include standard, target-independent definitions and methods used\n"
2027 << "// by the instruction selector.\n";
2028 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
2030 EmitNodeTransforms(OS);
2031 EmitPredicateFunctions(OS);
2033 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
2034 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2036 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2037 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2038 DEBUG(errs() << "\n");
2041 // At this point, we have full information about the 'Patterns' we need to
2042 // parse, both implicitly from instructions as well as from explicit pattern
2043 // definitions. Emit the resultant instruction selector.
2044 EmitInstructionSelector(OS);