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/Debug.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
24 //===----------------------------------------------------------------------===//
25 // DAGISelEmitter Helper methods
28 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
30 static bool NodeIsComplexPattern(TreePatternNode *N) {
31 return (N->isLeaf() &&
32 dynamic_cast<DefInit*>(N->getLeafValue()) &&
33 static_cast<DefInit*>(N->getLeafValue())->getDef()->
34 isSubClassOf("ComplexPattern"));
37 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
38 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
39 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
40 CodeGenDAGPatterns &CGP) {
42 dynamic_cast<DefInit*>(N->getLeafValue()) &&
43 static_cast<DefInit*>(N->getLeafValue())->getDef()->
44 isSubClassOf("ComplexPattern")) {
45 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
51 /// getPatternSize - Return the 'size' of this pattern. We want to match large
52 /// patterns before small ones. This is used to determine the size of a
54 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
55 assert((EMVT::isExtIntegerInVTs(P->getExtTypes()) ||
56 EMVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
57 P->getExtTypeNum(0) == MVT::isVoid ||
58 P->getExtTypeNum(0) == MVT::Flag ||
59 P->getExtTypeNum(0) == MVT::iPTR ||
60 P->getExtTypeNum(0) == MVT::iPTRAny) &&
61 "Not a valid pattern node to size!");
62 unsigned Size = 3; // The node itself.
63 // If the root node is a ConstantSDNode, increases its size.
64 // e.g. (set R32:$dst, 0).
65 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
68 // FIXME: This is a hack to statically increase the priority of patterns
69 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
70 // Later we can allow complexity / cost for each pattern to be (optionally)
71 // specified. To get best possible pattern match we'll need to dynamically
72 // calculate the complexity of all patterns a dag can potentially map to.
73 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
75 Size += AM->getNumOperands() * 3;
77 // If this node has some predicate function that must match, it adds to the
78 // complexity of this node.
79 if (!P->getPredicateFn().empty())
82 // Count children in the count if they are also nodes.
83 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
84 TreePatternNode *Child = P->getChild(i);
85 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
86 Size += getPatternSize(Child, CGP);
87 else if (Child->isLeaf()) {
88 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
89 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
90 else if (NodeIsComplexPattern(Child))
91 Size += getPatternSize(Child, CGP);
92 else if (!Child->getPredicateFn().empty())
100 /// getResultPatternCost - Compute the number of instructions for this pattern.
101 /// This is a temporary hack. We should really include the instruction
102 /// latencies in this calculation.
103 static unsigned getResultPatternCost(TreePatternNode *P,
104 CodeGenDAGPatterns &CGP) {
105 if (P->isLeaf()) return 0;
108 Record *Op = P->getOperator();
109 if (Op->isSubClassOf("Instruction")) {
111 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
112 if (II.usesCustomDAGSchedInserter)
115 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
116 Cost += getResultPatternCost(P->getChild(i), CGP);
120 /// getResultPatternCodeSize - Compute the code size of instructions for this
122 static unsigned getResultPatternSize(TreePatternNode *P,
123 CodeGenDAGPatterns &CGP) {
124 if (P->isLeaf()) return 0;
127 Record *Op = P->getOperator();
128 if (Op->isSubClassOf("Instruction")) {
129 Cost += Op->getValueAsInt("CodeSize");
131 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
132 Cost += getResultPatternSize(P->getChild(i), CGP);
136 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
137 // In particular, we want to match maximal patterns first and lowest cost within
138 // a particular complexity first.
139 struct PatternSortingPredicate {
140 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
141 CodeGenDAGPatterns &CGP;
143 bool operator()(const PatternToMatch *LHS,
144 const PatternToMatch *RHS) {
145 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
146 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
147 LHSSize += LHS->getAddedComplexity();
148 RHSSize += RHS->getAddedComplexity();
149 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
150 if (LHSSize < RHSSize) return false;
152 // If the patterns have equal complexity, compare generated instruction cost
153 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
154 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
155 if (LHSCost < RHSCost) return true;
156 if (LHSCost > RHSCost) return false;
158 return getResultPatternSize(LHS->getDstPattern(), CGP) <
159 getResultPatternSize(RHS->getDstPattern(), CGP);
163 /// getRegisterValueType - Look up and return the first ValueType of specified
164 /// RegisterClass record
165 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
166 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
167 return RC->getValueTypeNum(0);
172 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
173 /// type information from it.
174 static void RemoveAllTypes(TreePatternNode *N) {
177 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
178 RemoveAllTypes(N->getChild(i));
181 /// NodeHasProperty - return true if TreePatternNode has the specified
183 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
184 CodeGenDAGPatterns &CGP) {
186 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
188 return CP->hasProperty(Property);
191 Record *Operator = N->getOperator();
192 if (!Operator->isSubClassOf("SDNode")) return false;
194 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
197 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
198 CodeGenDAGPatterns &CGP) {
199 if (NodeHasProperty(N, Property, CGP))
202 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
203 TreePatternNode *Child = N->getChild(i);
204 if (PatternHasProperty(Child, Property, CGP))
211 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
212 return CGP.getSDNodeInfo(Op).getEnumName();
216 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
217 bool isStore = !N->isLeaf() &&
218 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
219 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
222 bool HasChain = false;
223 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
224 TreePatternNode *Child = N->getChild(i);
225 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
233 //===----------------------------------------------------------------------===//
234 // Node Transformation emitter implementation.
236 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
237 // Walk the pattern fragments, adding them to a map, which sorts them by
239 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
240 NXsByNameTy NXsByName;
242 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
244 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
246 OS << "\n// Node transformations.\n";
248 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
250 Record *SDNode = I->second.first;
251 std::string Code = I->second.second;
253 if (Code.empty()) continue; // Empty code? Skip it.
255 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
256 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
258 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
260 if (ClassName != "SDNode")
261 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
262 OS << Code << "\n}\n";
266 //===----------------------------------------------------------------------===//
267 // Predicate emitter implementation.
270 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
271 OS << "\n// Predicate functions.\n";
273 // Walk the pattern fragments, adding them to a map, which sorts them by
275 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
276 PFsByNameTy PFsByName;
278 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
280 PFsByName.insert(std::make_pair(I->first->getName(), *I));
283 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
285 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
286 TreePattern *P = I->second.second;
288 // If there is a code init for this fragment, emit the predicate code.
289 std::string Code = PatFragRecord->getValueAsCode("Predicate");
290 if (Code.empty()) continue;
292 if (P->getOnlyTree()->isLeaf())
293 OS << "inline bool Predicate_" << PatFragRecord->getName()
294 << "(SDNode *N) {\n";
296 std::string ClassName =
297 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
298 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
300 OS << "inline bool Predicate_" << PatFragRecord->getName()
301 << "(SDNode *" << C2 << ") {\n";
302 if (ClassName != "SDNode")
303 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
305 OS << Code << "\n}\n";
312 //===----------------------------------------------------------------------===//
313 // PatternCodeEmitter implementation.
315 class PatternCodeEmitter {
317 CodeGenDAGPatterns &CGP;
320 std::string PredicateCheck;
323 // Instruction selector pattern.
324 TreePatternNode *Pattern;
325 // Matched instruction.
326 TreePatternNode *Instruction;
328 // Node to name mapping
329 std::map<std::string, std::string> VariableMap;
330 // Node to operator mapping
331 std::map<std::string, Record*> OperatorMap;
332 // Name of the folded node which produces a flag.
333 std::pair<std::string, unsigned> FoldedFlag;
334 // Names of all the folded nodes which produce chains.
335 std::vector<std::pair<std::string, unsigned> > FoldedChains;
336 // Original input chain(s).
337 std::vector<std::pair<std::string, std::string> > OrigChains;
338 std::set<std::string> Duplicates;
340 /// LSI - Load/Store information.
341 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
342 /// for each memory access. This facilitates the use of AliasAnalysis in
344 std::vector<std::string> LSI;
346 /// GeneratedCode - This is the buffer that we emit code to. The first int
347 /// indicates whether this is an exit predicate (something that should be
348 /// tested, and if true, the match fails) [when 1], or normal code to emit
349 /// [when 0], or initialization code to emit [when 2].
350 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
351 /// GeneratedDecl - This is the set of all SDValue declarations needed for
352 /// the set of patterns for each top-level opcode.
353 std::set<std::string> &GeneratedDecl;
354 /// TargetOpcodes - The target specific opcodes used by the resulting
356 std::vector<std::string> &TargetOpcodes;
357 std::vector<std::string> &TargetVTs;
358 /// OutputIsVariadic - Records whether the instruction output pattern uses
359 /// variable_ops. This requires that the Emit function be passed an
360 /// additional argument to indicate where the input varargs operands
362 bool &OutputIsVariadic;
363 /// NumInputRootOps - Records the number of operands the root node of the
364 /// input pattern has. This information is used in the generated code to
365 /// pass to Emit functions when variable_ops processing is needed.
366 unsigned &NumInputRootOps;
368 std::string ChainName;
373 void emitCheck(const std::string &S) {
375 GeneratedCode.push_back(std::make_pair(1, S));
377 void emitCode(const std::string &S) {
379 GeneratedCode.push_back(std::make_pair(0, S));
381 void emitInit(const std::string &S) {
383 GeneratedCode.push_back(std::make_pair(2, S));
385 void emitDecl(const std::string &S) {
386 assert(!S.empty() && "Invalid declaration");
387 GeneratedDecl.insert(S);
389 void emitOpcode(const std::string &Opc) {
390 TargetOpcodes.push_back(Opc);
393 void emitVT(const std::string &VT) {
394 TargetVTs.push_back(VT);
398 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
399 TreePatternNode *pattern, TreePatternNode *instr,
400 std::vector<std::pair<unsigned, std::string> > &gc,
401 std::set<std::string> &gd,
402 std::vector<std::string> &to,
403 std::vector<std::string> &tv,
406 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
407 GeneratedCode(gc), GeneratedDecl(gd),
408 TargetOpcodes(to), TargetVTs(tv),
409 OutputIsVariadic(oiv), NumInputRootOps(niro),
410 TmpNo(0), OpcNo(0), VTNo(0) {}
412 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
413 /// if the match fails. At this point, we already know that the opcode for N
414 /// matches, and the SDNode for the result has the RootName specified name.
415 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
416 const std::string &RootName, const std::string &ChainSuffix,
419 // Save loads/stores matched by a pattern.
420 if (!N->isLeaf() && N->getName().empty()) {
421 if (NodeHasProperty(N, SDNPMemOperand, CGP))
422 LSI.push_back(RootName);
425 bool isRoot = (P == NULL);
426 // Emit instruction predicates. Each predicate is just a string for now.
428 // Record input varargs info.
429 NumInputRootOps = N->getNumChildren();
431 if (DisablePatternForFastISel(N, CGP))
434 emitCheck(PredicateCheck);
438 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
439 emitCheck("cast<ConstantSDNode>(" + RootName +
440 ")->getSignExtended() == " + itostr(II->getValue()));
442 } else if (!NodeIsComplexPattern(N)) {
443 assert(0 && "Cannot match this as a leaf value!");
448 // If this node has a name associated with it, capture it in VariableMap. If
449 // we already saw this in the pattern, emit code to verify dagness.
450 if (!N->getName().empty()) {
451 std::string &VarMapEntry = VariableMap[N->getName()];
452 if (VarMapEntry.empty()) {
453 VarMapEntry = RootName;
455 // If we get here, this is a second reference to a specific name. Since
456 // we already have checked that the first reference is valid, we don't
457 // have to recursively match it, just check that it's the same as the
458 // previously named thing.
459 emitCheck(VarMapEntry + " == " + RootName);
464 OperatorMap[N->getName()] = N->getOperator();
468 // Emit code to load the child nodes and match their contents recursively.
470 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
471 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
472 bool EmittedUseCheck = false;
477 // Multiple uses of actual result?
478 emitCheck(RootName + ".hasOneUse()");
479 EmittedUseCheck = true;
481 // If the immediate use can somehow reach this node through another
482 // path, then can't fold it either or it will create a cycle.
483 // e.g. In the following diagram, XX can reach ld through YY. If
484 // ld is folded into XX, then YY is both a predecessor and a successor
494 bool NeedCheck = P != Pattern;
496 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
498 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
499 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
500 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
501 PInfo.getNumOperands() > 1 ||
502 PInfo.hasProperty(SDNPHasChain) ||
503 PInfo.hasProperty(SDNPInFlag) ||
504 PInfo.hasProperty(SDNPOptInFlag);
508 std::string ParentName(RootName.begin(), RootName.end()-1);
509 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
517 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
518 "IsChainCompatible(" + ChainName + ".Val, " +
519 RootName + ".Val))");
520 OrigChains.push_back(std::make_pair(ChainName, RootName));
523 ChainName = "Chain" + ChainSuffix;
524 emitInit("SDValue " + ChainName + " = " + RootName +
529 // Don't fold any node which reads or writes a flag and has multiple uses.
530 // FIXME: We really need to separate the concepts of flag and "glue". Those
531 // real flag results, e.g. X86CMP output, can have multiple uses.
532 // FIXME: If the optional incoming flag does not exist. Then it is ok to
535 (PatternHasProperty(N, SDNPInFlag, CGP) ||
536 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
537 PatternHasProperty(N, SDNPOutFlag, CGP))) {
538 if (!EmittedUseCheck) {
539 // Multiple uses of actual result?
540 emitCheck(RootName + ".hasOneUse()");
544 // If there is a node predicate for this, emit the call.
545 if (!N->getPredicateFn().empty())
546 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
549 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
550 // a constant without a predicate fn that has more that one bit set, handle
551 // this as a special case. This is usually for targets that have special
552 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
553 // handling stuff). Using these instructions is often far more efficient
554 // than materializing the constant. Unfortunately, both the instcombiner
555 // and the dag combiner can often infer that bits are dead, and thus drop
556 // them from the mask in the dag. For example, it might turn 'AND X, 255'
557 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
560 (N->getOperator()->getName() == "and" ||
561 N->getOperator()->getName() == "or") &&
562 N->getChild(1)->isLeaf() &&
563 N->getChild(1)->getPredicateFn().empty()) {
564 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
565 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
566 emitInit("SDValue " + RootName + "0" + " = " +
567 RootName + ".getOperand(" + utostr(0) + ");");
568 emitInit("SDValue " + RootName + "1" + " = " +
569 RootName + ".getOperand(" + utostr(1) + ");");
571 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
572 const char *MaskPredicate = N->getOperator()->getName() == "or"
573 ? "CheckOrMask(" : "CheckAndMask(";
574 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
575 RootName + "1), " + itostr(II->getValue()) + ")");
577 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
578 ChainSuffix + utostr(0), FoundChain);
584 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
585 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
586 RootName + ".getOperand(" +utostr(OpNo) + ");");
588 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
589 ChainSuffix + utostr(OpNo), FoundChain);
592 // Handle cases when root is a complex pattern.
593 const ComplexPattern *CP;
594 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
595 std::string Fn = CP->getSelectFunc();
596 unsigned NumOps = CP->getNumOperands();
597 for (unsigned i = 0; i < NumOps; ++i) {
598 emitDecl("CPTmp" + utostr(i));
599 emitCode("SDValue CPTmp" + utostr(i) + ";");
601 if (CP->hasProperty(SDNPHasChain)) {
602 emitDecl("CPInChain");
603 emitDecl("Chain" + ChainSuffix);
604 emitCode("SDValue CPInChain;");
605 emitCode("SDValue Chain" + ChainSuffix + ";");
608 std::string Code = Fn + "(" + RootName + ", " + RootName;
609 for (unsigned i = 0; i < NumOps; i++)
610 Code += ", CPTmp" + utostr(i);
611 if (CP->hasProperty(SDNPHasChain)) {
612 ChainName = "Chain" + ChainSuffix;
613 Code += ", CPInChain, Chain" + ChainSuffix;
615 emitCheck(Code + ")");
619 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
620 const std::string &RootName,
621 const std::string &ParentRootName,
622 const std::string &ChainSuffix, bool &FoundChain) {
623 if (!Child->isLeaf()) {
624 // If it's not a leaf, recursively match.
625 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
626 emitCheck(RootName + ".getOpcode() == " +
627 CInfo.getEnumName());
628 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
629 bool HasChain = false;
630 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
632 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
634 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
635 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
636 "Pattern folded multiple nodes which produce flags?");
637 FoldedFlag = std::make_pair(RootName,
638 CInfo.getNumResults() + (unsigned)HasChain);
641 // If this child has a name associated with it, capture it in VarMap. If
642 // we already saw this in the pattern, emit code to verify dagness.
643 if (!Child->getName().empty()) {
644 std::string &VarMapEntry = VariableMap[Child->getName()];
645 if (VarMapEntry.empty()) {
646 VarMapEntry = RootName;
648 // If we get here, this is a second reference to a specific name.
649 // Since we already have checked that the first reference is valid,
650 // we don't have to recursively match it, just check that it's the
651 // same as the previously named thing.
652 emitCheck(VarMapEntry + " == " + RootName);
653 Duplicates.insert(RootName);
658 // Handle leaves of various types.
659 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
660 Record *LeafRec = DI->getDef();
661 if (LeafRec->isSubClassOf("RegisterClass") ||
662 LeafRec->getName() == "ptr_rc") {
663 // Handle register references. Nothing to do here.
664 } else if (LeafRec->isSubClassOf("Register")) {
665 // Handle register references.
666 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
667 // Handle complex pattern.
668 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
669 std::string Fn = CP->getSelectFunc();
670 unsigned NumOps = CP->getNumOperands();
671 for (unsigned i = 0; i < NumOps; ++i) {
672 emitDecl("CPTmp" + utostr(i));
673 emitCode("SDValue CPTmp" + utostr(i) + ";");
675 if (CP->hasProperty(SDNPHasChain)) {
676 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
677 FoldedChains.push_back(std::make_pair("CPInChain",
678 PInfo.getNumResults()));
679 ChainName = "Chain" + ChainSuffix;
680 emitDecl("CPInChain");
682 emitCode("SDValue CPInChain;");
683 emitCode("SDValue " + ChainName + ";");
686 std::string Code = Fn + "(";
687 if (CP->hasAttribute(CPAttrParentAsRoot)) {
688 Code += ParentRootName + ", ";
692 if (CP->hasProperty(SDNPHasChain)) {
693 std::string ParentName(RootName.begin(), RootName.end()-1);
694 Code += ParentName + ", ";
697 for (unsigned i = 0; i < NumOps; i++)
698 Code += ", CPTmp" + utostr(i);
699 if (CP->hasProperty(SDNPHasChain))
700 Code += ", CPInChain, Chain" + ChainSuffix;
701 emitCheck(Code + ")");
702 } else if (LeafRec->getName() == "srcvalue") {
703 // Place holder for SRCVALUE nodes. Nothing to do here.
704 } else if (LeafRec->isSubClassOf("ValueType")) {
705 // Make sure this is the specified value type.
706 emitCheck("cast<VTSDNode>(" + RootName +
707 ")->getVT() == MVT::" + LeafRec->getName());
708 } else if (LeafRec->isSubClassOf("CondCode")) {
709 // Make sure this is the specified cond code.
710 emitCheck("cast<CondCodeSDNode>(" + RootName +
711 ")->get() == ISD::" + LeafRec->getName());
717 assert(0 && "Unknown leaf type!");
720 // If there is a node predicate for this, emit the call.
721 if (!Child->getPredicateFn().empty())
722 emitCheck(Child->getPredicateFn() + "(" + RootName +
724 } else if (IntInit *II =
725 dynamic_cast<IntInit*>(Child->getLeafValue())) {
726 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
727 unsigned CTmp = TmpNo++;
728 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
729 RootName + ")->getSignExtended();");
731 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
736 assert(0 && "Unknown leaf type!");
741 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
742 /// we actually have to build a DAG!
743 std::vector<std::string>
744 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
745 bool InFlagDecled, bool ResNodeDecled,
746 bool LikeLeaf = false, bool isRoot = false) {
747 // List of arguments of getTargetNode() or SelectNodeTo().
748 std::vector<std::string> NodeOps;
749 // This is something selected from the pattern we matched.
750 if (!N->getName().empty()) {
751 const std::string &VarName = N->getName();
752 std::string Val = VariableMap[VarName];
753 bool ModifiedVal = false;
755 cerr << "Variable '" << VarName << " referenced but not defined "
756 << "and not caught earlier!\n";
759 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
760 // Already selected this operand, just return the tmpval.
761 NodeOps.push_back(Val);
765 const ComplexPattern *CP;
766 unsigned ResNo = TmpNo++;
767 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
768 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
769 std::string CastType;
770 std::string TmpVar = "Tmp" + utostr(ResNo);
771 switch (N->getTypeNum(0)) {
773 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
774 << " type as an immediate constant. Aborting\n";
776 case MVT::i1: CastType = "bool"; break;
777 case MVT::i8: CastType = "unsigned char"; break;
778 case MVT::i16: CastType = "unsigned short"; break;
779 case MVT::i32: CastType = "unsigned"; break;
780 case MVT::i64: CastType = "uint64_t"; break;
782 emitCode("SDValue " + TmpVar +
783 " = CurDAG->getTargetConstant(((" + CastType +
784 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
785 getEnumName(N->getTypeNum(0)) + ");");
786 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
787 // value if used multiple times by this pattern result.
790 NodeOps.push_back(Val);
791 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
792 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
793 std::string TmpVar = "Tmp" + utostr(ResNo);
794 emitCode("SDValue " + TmpVar +
795 " = CurDAG->getTargetConstantFP(cast<ConstantFPSDNode>(" +
796 Val + ")->getValueAPF(), cast<ConstantFPSDNode>(" + Val +
797 ")->getValueType(0));");
798 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
799 // value if used multiple times by this pattern result.
802 NodeOps.push_back(Val);
803 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
804 Record *Op = OperatorMap[N->getName()];
805 // Transform ExternalSymbol to TargetExternalSymbol
806 if (Op && Op->getName() == "externalsym") {
807 std::string TmpVar = "Tmp"+utostr(ResNo);
808 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
809 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
810 Val + ")->getSymbol(), " +
811 getEnumName(N->getTypeNum(0)) + ");");
812 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
813 // this value if used multiple times by this pattern result.
817 NodeOps.push_back(Val);
818 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
819 || N->getOperator()->getName() == "tglobaltlsaddr")) {
820 Record *Op = OperatorMap[N->getName()];
821 // Transform GlobalAddress to TargetGlobalAddress
822 if (Op && (Op->getName() == "globaladdr" ||
823 Op->getName() == "globaltlsaddr")) {
824 std::string TmpVar = "Tmp" + utostr(ResNo);
825 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
826 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
827 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
829 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
830 // this value if used multiple times by this pattern result.
834 NodeOps.push_back(Val);
835 } else if (!N->isLeaf()
836 && (N->getOperator()->getName() == "texternalsym"
837 || N->getOperator()->getName() == "tconstpool")) {
838 // Do not rewrite the variable name, since we don't generate a new
840 NodeOps.push_back(Val);
841 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
842 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
843 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
844 NodeOps.push_back("CPTmp" + utostr(i));
847 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
848 // node even if it isn't one. Don't select it.
850 emitCode("AddToISelQueue(" + Val + ");");
851 if (isRoot && N->isLeaf()) {
852 emitCode("ReplaceUses(N, " + Val + ");");
853 emitCode("return NULL;");
856 NodeOps.push_back(Val);
860 VariableMap[VarName] = Val;
865 // If this is an explicit register reference, handle it.
866 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
867 unsigned ResNo = TmpNo++;
868 if (DI->getDef()->isSubClassOf("Register")) {
869 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
870 getQualifiedName(DI->getDef()) + ", " +
871 getEnumName(N->getTypeNum(0)) + ");");
872 NodeOps.push_back("Tmp" + utostr(ResNo));
874 } else if (DI->getDef()->getName() == "zero_reg") {
875 emitCode("SDValue Tmp" + utostr(ResNo) +
876 " = CurDAG->getRegister(0, " +
877 getEnumName(N->getTypeNum(0)) + ");");
878 NodeOps.push_back("Tmp" + utostr(ResNo));
881 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
882 unsigned ResNo = TmpNo++;
883 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
884 emitCode("SDValue Tmp" + utostr(ResNo) +
885 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
886 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
887 NodeOps.push_back("Tmp" + utostr(ResNo));
894 assert(0 && "Unknown leaf type!");
898 Record *Op = N->getOperator();
899 if (Op->isSubClassOf("Instruction")) {
900 const CodeGenTarget &CGT = CGP.getTargetInfo();
901 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
902 const DAGInstruction &Inst = CGP.getInstruction(Op);
903 const TreePattern *InstPat = Inst.getPattern();
904 // FIXME: Assume actual pattern comes before "implicit".
905 TreePatternNode *InstPatNode =
906 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
907 : (InstPat ? InstPat->getTree(0) : NULL);
908 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
909 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
911 bool IsVariadic = isRoot && II.isVariadic;
912 // FIXME: fix how we deal with physical register operands.
913 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
914 bool HasImpResults = isRoot && DstRegs.size() > 0;
915 bool NodeHasOptInFlag = isRoot &&
916 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
917 bool NodeHasInFlag = isRoot &&
918 PatternHasProperty(Pattern, SDNPInFlag, CGP);
919 bool NodeHasOutFlag = isRoot &&
920 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
921 bool NodeHasChain = InstPatNode &&
922 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
923 bool InputHasChain = isRoot &&
924 NodeHasProperty(Pattern, SDNPHasChain, CGP);
925 unsigned NumResults = Inst.getNumResults();
926 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
928 // Record output varargs info.
929 OutputIsVariadic = IsVariadic;
931 if (NodeHasOptInFlag) {
932 emitCode("bool HasInFlag = "
933 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
936 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
938 // How many results is this pattern expected to produce?
939 unsigned NumPatResults = 0;
940 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
941 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
942 if (VT != MVT::isVoid && VT != MVT::Flag)
946 if (OrigChains.size() > 0) {
947 // The original input chain is being ignored. If it is not just
948 // pointing to the op that's being folded, we should create a
949 // TokenFactor with it and the chain of the folded op as the new chain.
950 // We could potentially be doing multiple levels of folding, in that
951 // case, the TokenFactor can have more operands.
952 emitCode("SmallVector<SDValue, 8> InChains;");
953 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
954 emitCode("if (" + OrigChains[i].first + ".Val != " +
955 OrigChains[i].second + ".Val) {");
956 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
957 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
960 emitCode("AddToISelQueue(" + ChainName + ");");
961 emitCode("InChains.push_back(" + ChainName + ");");
962 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
963 "&InChains[0], InChains.size());");
966 // Loop over all of the operands of the instruction pattern, emitting code
967 // to fill them all in. The node 'N' usually has number children equal to
968 // the number of input operands of the instruction. However, in cases
969 // where there are predicate operands for an instruction, we need to fill
970 // in the 'execute always' values. Match up the node operands to the
971 // instruction operands to do this.
972 std::vector<std::string> AllOps;
973 for (unsigned ChildNo = 0, InstOpNo = NumResults;
974 InstOpNo != II.OperandList.size(); ++InstOpNo) {
975 std::vector<std::string> Ops;
977 // Determine what to emit for this operand.
978 Record *OperandNode = II.OperandList[InstOpNo].Rec;
979 if ((OperandNode->isSubClassOf("PredicateOperand") ||
980 OperandNode->isSubClassOf("OptionalDefOperand")) &&
981 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
982 // This is a predicate or optional def operand; emit the
983 // 'default ops' operands.
984 const DAGDefaultOperand &DefaultOp =
985 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
986 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
987 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
988 InFlagDecled, ResNodeDecled);
989 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
992 // Otherwise this is a normal operand or a predicate operand without
993 // 'execute always'; emit it.
994 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
995 InFlagDecled, ResNodeDecled);
996 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1001 // Emit all the chain and CopyToReg stuff.
1002 bool ChainEmitted = NodeHasChain;
1004 emitCode("AddToISelQueue(" + ChainName + ");");
1005 if (NodeHasInFlag || HasImpInputs)
1006 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1007 InFlagDecled, ResNodeDecled, true);
1008 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1009 if (!InFlagDecled) {
1010 emitCode("SDValue InFlag(0, 0);");
1011 InFlagDecled = true;
1013 if (NodeHasOptInFlag) {
1014 emitCode("if (HasInFlag) {");
1015 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1016 emitCode(" AddToISelQueue(InFlag);");
1021 unsigned ResNo = TmpNo++;
1023 unsigned OpsNo = OpcNo;
1024 std::string CodePrefix;
1025 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1026 std::deque<std::string> After;
1027 std::string NodeName;
1029 NodeName = "Tmp" + utostr(ResNo);
1030 CodePrefix = "SDValue " + NodeName + "(";
1032 NodeName = "ResNode";
1033 if (!ResNodeDecled) {
1034 CodePrefix = "SDNode *" + NodeName + " = ";
1035 ResNodeDecled = true;
1037 CodePrefix = NodeName + " = ";
1040 std::string Code = "Opc" + utostr(OpcNo);
1042 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1044 // Output order: results, chain, flags
1046 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1047 Code += ", VT" + utostr(VTNo);
1048 emitVT(getEnumName(N->getTypeNum(0)));
1050 // Add types for implicit results in physical registers, scheduler will
1051 // care of adding copyfromreg nodes.
1052 for (unsigned i = 0; i < NumDstRegs; i++) {
1053 Record *RR = DstRegs[i];
1054 if (RR->isSubClassOf("Register")) {
1055 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1056 Code += ", " + getEnumName(RVT);
1060 Code += ", MVT::Other";
1062 Code += ", MVT::Flag";
1066 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1067 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1070 // Figure out whether any operands at the end of the op list are not
1071 // part of the variable section.
1072 std::string EndAdjust;
1073 if (NodeHasInFlag || HasImpInputs)
1074 EndAdjust = "-1"; // Always has one flag.
1075 else if (NodeHasOptInFlag)
1076 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1078 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1079 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1081 emitCode(" AddToISelQueue(N.getOperand(i));");
1082 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1086 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1088 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1089 std::vector<std::string>::const_iterator mi, mie;
1090 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1091 emitCode("SDValue LSI_" + *mi + " = "
1092 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1093 *mi + ")->getMemOperand());");
1095 emitCode("Ops" + utostr(OpsNo) + ".push_back(LSI_" + *mi + ");");
1097 AllOps.push_back("LSI_" + *mi);
1103 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1105 AllOps.push_back(ChainName);
1109 if (NodeHasInFlag || HasImpInputs)
1110 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1111 else if (NodeHasOptInFlag) {
1112 emitCode("if (HasInFlag)");
1113 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1115 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1117 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1118 AllOps.push_back("InFlag");
1120 unsigned NumOps = AllOps.size();
1122 if (!NodeHasOptInFlag && NumOps < 4) {
1123 for (unsigned i = 0; i != NumOps; ++i)
1124 Code += ", " + AllOps[i];
1126 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1127 for (unsigned i = 0; i != NumOps; ++i) {
1128 OpsCode += AllOps[i];
1132 emitCode(OpsCode + " };");
1133 Code += ", Ops" + utostr(OpsNo) + ", ";
1134 if (NodeHasOptInFlag) {
1135 Code += "HasInFlag ? ";
1136 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1138 Code += utostr(NumOps);
1145 std::vector<std::string> ReplaceFroms;
1146 std::vector<std::string> ReplaceTos;
1148 NodeOps.push_back("Tmp" + utostr(ResNo));
1151 if (NodeHasOutFlag) {
1152 if (!InFlagDecled) {
1153 After.push_back("SDValue InFlag(ResNode, " +
1154 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1156 InFlagDecled = true;
1158 After.push_back("InFlag = SDValue(ResNode, " +
1159 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1163 if (FoldedChains.size() > 0) {
1165 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1166 ReplaceFroms.push_back("SDValue(" +
1167 FoldedChains[j].first + ".Val, " +
1168 utostr(FoldedChains[j].second) +
1170 ReplaceTos.push_back("SDValue(ResNode, " +
1171 utostr(NumResults+NumDstRegs) + ")");
1175 if (NodeHasOutFlag) {
1176 if (FoldedFlag.first != "") {
1177 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".Val, " +
1178 utostr(FoldedFlag.second) + ")");
1179 ReplaceTos.push_back("InFlag");
1181 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1182 ReplaceFroms.push_back("SDValue(N.Val, " +
1183 utostr(NumPatResults + (unsigned)InputHasChain)
1185 ReplaceTos.push_back("InFlag");
1189 if (!ReplaceFroms.empty() && InputHasChain) {
1190 ReplaceFroms.push_back("SDValue(N.Val, " +
1191 utostr(NumPatResults) + ")");
1192 ReplaceTos.push_back("SDValue(" + ChainName + ".Val, " +
1193 ChainName + ".ResNo" + ")");
1194 ChainAssignmentNeeded |= NodeHasChain;
1197 // User does not expect the instruction would produce a chain!
1198 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1200 } else if (InputHasChain && !NodeHasChain) {
1201 // One of the inner node produces a chain.
1202 if (NodeHasOutFlag) {
1203 ReplaceFroms.push_back("SDValue(N.Val, " +
1204 utostr(NumPatResults+1) +
1206 ReplaceTos.push_back("SDValue(ResNode, N.ResNo-1)");
1208 ReplaceFroms.push_back("SDValue(N.Val, " +
1209 utostr(NumPatResults) + ")");
1210 ReplaceTos.push_back(ChainName);
1214 if (ChainAssignmentNeeded) {
1215 // Remember which op produces the chain.
1216 std::string ChainAssign;
1218 ChainAssign = ChainName + " = SDValue(" + NodeName +
1219 ".Val, " + utostr(NumResults+NumDstRegs) + ");";
1221 ChainAssign = ChainName + " = SDValue(" + NodeName +
1222 ", " + utostr(NumResults+NumDstRegs) + ");";
1224 After.push_front(ChainAssign);
1227 if (ReplaceFroms.size() == 1) {
1228 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1229 ReplaceTos[0] + ");");
1230 } else if (!ReplaceFroms.empty()) {
1231 After.push_back("const SDValue Froms[] = {");
1232 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1233 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1234 After.push_back("};");
1235 After.push_back("const SDValue Tos[] = {");
1236 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1237 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1238 After.push_back("};");
1239 After.push_back("ReplaceUses(Froms, Tos, " +
1240 itostr(ReplaceFroms.size()) + ");");
1243 // We prefer to use SelectNodeTo since it avoids allocation when
1244 // possible and it avoids CSE map recalculation for the node's
1245 // users, however it's tricky to use in a non-root context.
1247 // We also don't use if the pattern replacement is being used to
1248 // jettison a chain result, since morphing the node in place
1249 // would leave users of the chain dangling.
1251 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1252 Code = "CurDAG->getTargetNode(" + Code;
1254 Code = "CurDAG->SelectNodeTo(N.Val, " + Code;
1258 CodePrefix = "return ";
1260 After.push_back("return ResNode;");
1263 emitCode(CodePrefix + Code + ");");
1264 for (unsigned i = 0, e = After.size(); i != e; ++i)
1268 } else if (Op->isSubClassOf("SDNodeXForm")) {
1269 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1270 // PatLeaf node - the operand may or may not be a leaf node. But it should
1272 std::vector<std::string> Ops =
1273 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1274 ResNodeDecled, true);
1275 unsigned ResNo = TmpNo++;
1276 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1277 + "(" + Ops.back() + ".Val);");
1278 NodeOps.push_back("Tmp" + utostr(ResNo));
1280 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1285 throw std::string("Unknown node in result pattern!");
1289 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1290 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1291 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1292 /// for, this returns true otherwise false if Pat has all types.
1293 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1294 const std::string &Prefix, bool isRoot = false) {
1296 if (Pat->getExtTypes() != Other->getExtTypes()) {
1297 // Move a type over from 'other' to 'pat'.
1298 Pat->setTypes(Other->getExtTypes());
1299 // The top level node type is checked outside of the select function.
1301 emitCheck(Prefix + ".Val->getValueType(0) == " +
1302 getName(Pat->getTypeNum(0)));
1307 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1308 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1309 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1310 Prefix + utostr(OpNo)))
1316 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1318 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1319 bool &ChainEmitted, bool &InFlagDecled,
1320 bool &ResNodeDecled, bool isRoot = false) {
1321 const CodeGenTarget &T = CGP.getTargetInfo();
1323 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1324 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1325 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1326 TreePatternNode *Child = N->getChild(i);
1327 if (!Child->isLeaf()) {
1328 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1329 InFlagDecled, ResNodeDecled);
1331 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1332 if (!Child->getName().empty()) {
1333 std::string Name = RootName + utostr(OpNo);
1334 if (Duplicates.find(Name) != Duplicates.end())
1335 // A duplicate! Do not emit a copy for this node.
1339 Record *RR = DI->getDef();
1340 if (RR->isSubClassOf("Register")) {
1341 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1342 if (RVT == MVT::Flag) {
1343 if (!InFlagDecled) {
1344 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1345 InFlagDecled = true;
1347 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1348 emitCode("AddToISelQueue(InFlag);");
1350 if (!ChainEmitted) {
1351 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1352 ChainName = "Chain";
1353 ChainEmitted = true;
1355 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1356 if (!InFlagDecled) {
1357 emitCode("SDValue InFlag(0, 0);");
1358 InFlagDecled = true;
1360 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1361 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1362 ", " + getQualifiedName(RR) +
1363 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1364 ResNodeDecled = true;
1365 emitCode(ChainName + " = SDValue(ResNode, 0);");
1366 emitCode("InFlag = SDValue(ResNode, 1);");
1374 if (!InFlagDecled) {
1375 emitCode("SDValue InFlag = " + RootName +
1376 ".getOperand(" + utostr(OpNo) + ");");
1377 InFlagDecled = true;
1379 emitCode("InFlag = " + RootName +
1380 ".getOperand(" + utostr(OpNo) + ");");
1381 emitCode("AddToISelQueue(InFlag);");
1386 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1387 /// stream to match the pattern, and generate the code for the match if it
1388 /// succeeds. Returns true if the pattern is not guaranteed to match.
1389 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1390 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1391 std::set<std::string> &GeneratedDecl,
1392 std::vector<std::string> &TargetOpcodes,
1393 std::vector<std::string> &TargetVTs,
1394 bool &OutputIsVariadic,
1395 unsigned &NumInputRootOps) {
1396 OutputIsVariadic = false;
1397 NumInputRootOps = 0;
1399 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1400 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1401 GeneratedCode, GeneratedDecl,
1402 TargetOpcodes, TargetVTs,
1403 OutputIsVariadic, NumInputRootOps);
1405 // Emit the matcher, capturing named arguments in VariableMap.
1406 bool FoundChain = false;
1407 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1409 // TP - Get *SOME* tree pattern, we don't care which.
1410 TreePattern &TP = *CGP.pf_begin()->second;
1412 // At this point, we know that we structurally match the pattern, but the
1413 // types of the nodes may not match. Figure out the fewest number of type
1414 // comparisons we need to emit. For example, if there is only one integer
1415 // type supported by a target, there should be no type comparisons at all for
1416 // integer patterns!
1418 // To figure out the fewest number of type checks needed, clone the pattern,
1419 // remove the types, then perform type inference on the pattern as a whole.
1420 // If there are unresolved types, emit an explicit check for those types,
1421 // apply the type to the tree, then rerun type inference. Iterate until all
1422 // types are resolved.
1424 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1425 RemoveAllTypes(Pat);
1428 // Resolve/propagate as many types as possible.
1430 bool MadeChange = true;
1432 MadeChange = Pat->ApplyTypeConstraints(TP,
1433 true/*Ignore reg constraints*/);
1435 assert(0 && "Error: could not find consistent types for something we"
1436 " already decided was ok!");
1440 // Insert a check for an unresolved type and add it to the tree. If we find
1441 // an unresolved type to add a check for, this returns true and we iterate,
1442 // otherwise we are done.
1443 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1445 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1446 false, false, false, true);
1450 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1451 /// a line causes any of them to be empty, remove them and return true when
1453 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1454 std::vector<std::pair<unsigned, std::string> > > >
1456 bool ErasedPatterns = false;
1457 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1458 Patterns[i].second.pop_back();
1459 if (Patterns[i].second.empty()) {
1460 Patterns.erase(Patterns.begin()+i);
1462 ErasedPatterns = true;
1465 return ErasedPatterns;
1468 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1469 /// code together between the patterns.
1470 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1471 std::vector<std::pair<unsigned, std::string> > > >
1472 &Patterns, unsigned Indent,
1474 typedef std::pair<unsigned, std::string> CodeLine;
1475 typedef std::vector<CodeLine> CodeList;
1476 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1478 if (Patterns.empty()) return;
1480 // Figure out how many patterns share the next code line. Explicitly copy
1481 // FirstCodeLine so that we don't invalidate a reference when changing
1483 const CodeLine FirstCodeLine = Patterns.back().second.back();
1484 unsigned LastMatch = Patterns.size()-1;
1485 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1488 // If not all patterns share this line, split the list into two pieces. The
1489 // first chunk will use this line, the second chunk won't.
1490 if (LastMatch != 0) {
1491 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1492 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1494 // FIXME: Emit braces?
1495 if (Shared.size() == 1) {
1496 const PatternToMatch &Pattern = *Shared.back().first;
1497 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1498 Pattern.getSrcPattern()->print(OS);
1499 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1500 Pattern.getDstPattern()->print(OS);
1502 unsigned AddedComplexity = Pattern.getAddedComplexity();
1503 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1504 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1506 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1508 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1510 if (FirstCodeLine.first != 1) {
1511 OS << std::string(Indent, ' ') << "{\n";
1514 EmitPatterns(Shared, Indent, OS);
1515 if (FirstCodeLine.first != 1) {
1517 OS << std::string(Indent, ' ') << "}\n";
1520 if (Other.size() == 1) {
1521 const PatternToMatch &Pattern = *Other.back().first;
1522 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1523 Pattern.getSrcPattern()->print(OS);
1524 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1525 Pattern.getDstPattern()->print(OS);
1527 unsigned AddedComplexity = Pattern.getAddedComplexity();
1528 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1529 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1531 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1533 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1535 EmitPatterns(Other, Indent, OS);
1539 // Remove this code from all of the patterns that share it.
1540 bool ErasedPatterns = EraseCodeLine(Patterns);
1542 bool isPredicate = FirstCodeLine.first == 1;
1544 // Otherwise, every pattern in the list has this line. Emit it.
1547 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1549 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1551 // If the next code line is another predicate, and if all of the pattern
1552 // in this group share the same next line, emit it inline now. Do this
1553 // until we run out of common predicates.
1554 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1555 // Check that all of fhe patterns in Patterns end with the same predicate.
1556 bool AllEndWithSamePredicate = true;
1557 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1558 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1559 AllEndWithSamePredicate = false;
1562 // If all of the predicates aren't the same, we can't share them.
1563 if (!AllEndWithSamePredicate) break;
1565 // Otherwise we can. Emit it shared now.
1566 OS << " &&\n" << std::string(Indent+4, ' ')
1567 << Patterns.back().second.back().second;
1568 ErasedPatterns = EraseCodeLine(Patterns);
1575 EmitPatterns(Patterns, Indent, OS);
1578 OS << std::string(Indent-2, ' ') << "}\n";
1581 static std::string getLegalCName(std::string OpName) {
1582 std::string::size_type pos = OpName.find("::");
1583 if (pos != std::string::npos)
1584 OpName.replace(pos, 2, "_");
1588 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1589 const CodeGenTarget &Target = CGP.getTargetInfo();
1591 // Get the namespace to insert instructions into.
1592 std::string InstNS = Target.getInstNamespace();
1593 if (!InstNS.empty()) InstNS += "::";
1595 // Group the patterns by their top-level opcodes.
1596 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1597 // All unique target node emission functions.
1598 std::map<std::string, unsigned> EmitFunctions;
1599 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1600 E = CGP.ptm_end(); I != E; ++I) {
1601 const PatternToMatch &Pattern = *I;
1603 TreePatternNode *Node = Pattern.getSrcPattern();
1604 if (!Node->isLeaf()) {
1605 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1606 push_back(&Pattern);
1608 const ComplexPattern *CP;
1609 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1610 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1611 push_back(&Pattern);
1612 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1613 std::vector<Record*> OpNodes = CP->getRootNodes();
1614 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1615 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1616 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1620 cerr << "Unrecognized opcode '";
1622 cerr << "' on tree pattern '";
1623 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1629 // For each opcode, there might be multiple select functions, one per
1630 // ValueType of the node (or its first operand if it doesn't produce a
1631 // non-chain result.
1632 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1634 // Emit one Select_* method for each top-level opcode. We do this instead of
1635 // emitting one giant switch statement to support compilers where this will
1636 // result in the recursive functions taking less stack space.
1637 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1638 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1639 PBOI != E; ++PBOI) {
1640 const std::string &OpName = PBOI->first;
1641 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1642 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1644 // We want to emit all of the matching code now. However, we want to emit
1645 // the matches in order of minimal cost. Sort the patterns so the least
1646 // cost one is at the start.
1647 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1648 PatternSortingPredicate(CGP));
1650 // Split them into groups by type.
1651 std::map<MVT::SimpleValueType,
1652 std::vector<const PatternToMatch*> > PatternsByType;
1653 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1654 const PatternToMatch *Pat = PatternsOfOp[i];
1655 TreePatternNode *SrcPat = Pat->getSrcPattern();
1656 MVT::SimpleValueType VT = SrcPat->getTypeNum(0);
1657 std::map<MVT::SimpleValueType,
1658 std::vector<const PatternToMatch*> >::iterator TI =
1659 PatternsByType.find(VT);
1660 if (TI != PatternsByType.end())
1661 TI->second.push_back(Pat);
1663 std::vector<const PatternToMatch*> PVec;
1664 PVec.push_back(Pat);
1665 PatternsByType.insert(std::make_pair(VT, PVec));
1669 for (std::map<MVT::SimpleValueType,
1670 std::vector<const PatternToMatch*> >::iterator
1671 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1673 MVT::SimpleValueType OpVT = II->first;
1674 std::vector<const PatternToMatch*> &Patterns = II->second;
1675 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1676 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1678 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1679 std::vector<std::vector<std::string> > PatternOpcodes;
1680 std::vector<std::vector<std::string> > PatternVTs;
1681 std::vector<std::set<std::string> > PatternDecls;
1682 std::vector<bool> OutputIsVariadicFlags;
1683 std::vector<unsigned> NumInputRootOpsCounts;
1684 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1685 CodeList GeneratedCode;
1686 std::set<std::string> GeneratedDecl;
1687 std::vector<std::string> TargetOpcodes;
1688 std::vector<std::string> TargetVTs;
1689 bool OutputIsVariadic;
1690 unsigned NumInputRootOps;
1691 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1692 TargetOpcodes, TargetVTs,
1693 OutputIsVariadic, NumInputRootOps);
1694 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1695 PatternDecls.push_back(GeneratedDecl);
1696 PatternOpcodes.push_back(TargetOpcodes);
1697 PatternVTs.push_back(TargetVTs);
1698 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1699 NumInputRootOpsCounts.push_back(NumInputRootOps);
1702 // Scan the code to see if all of the patterns are reachable and if it is
1703 // possible that the last one might not match.
1704 bool mightNotMatch = true;
1705 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1706 CodeList &GeneratedCode = CodeForPatterns[i].second;
1707 mightNotMatch = false;
1709 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1710 if (GeneratedCode[j].first == 1) { // predicate.
1711 mightNotMatch = true;
1716 // If this pattern definitely matches, and if it isn't the last one, the
1717 // patterns after it CANNOT ever match. Error out.
1718 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1719 cerr << "Pattern '";
1720 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1721 cerr << "' is impossible to select!\n";
1726 // Factor target node emission code (emitted by EmitResultCode) into
1727 // separate functions. Uniquing and share them among all instruction
1728 // selection routines.
1729 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1730 CodeList &GeneratedCode = CodeForPatterns[i].second;
1731 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1732 std::vector<std::string> &TargetVTs = PatternVTs[i];
1733 std::set<std::string> Decls = PatternDecls[i];
1734 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1735 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1736 std::vector<std::string> AddedInits;
1737 int CodeSize = (int)GeneratedCode.size();
1739 for (int j = CodeSize-1; j >= 0; --j) {
1740 if (LastPred == -1 && GeneratedCode[j].first == 1)
1742 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1743 AddedInits.push_back(GeneratedCode[j].second);
1746 std::string CalleeCode = "(const SDValue &N";
1747 std::string CallerCode = "(N";
1748 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1749 CalleeCode += ", unsigned Opc" + utostr(j);
1750 CallerCode += ", " + TargetOpcodes[j];
1752 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1753 CalleeCode += ", MVT VT" + utostr(j);
1754 CallerCode += ", " + TargetVTs[j];
1756 for (std::set<std::string>::iterator
1757 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1758 std::string Name = *I;
1759 CalleeCode += ", SDValue &" + Name;
1760 CallerCode += ", " + Name;
1763 if (OutputIsVariadic) {
1764 CalleeCode += ", unsigned NumInputRootOps";
1765 CallerCode += ", " + utostr(NumInputRootOps);
1770 // Prevent emission routines from being inlined to reduce selection
1771 // routines stack frame sizes.
1772 CalleeCode += "DISABLE_INLINE ";
1773 CalleeCode += "{\n";
1775 for (std::vector<std::string>::const_reverse_iterator
1776 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1777 CalleeCode += " " + *I + "\n";
1779 for (int j = LastPred+1; j < CodeSize; ++j)
1780 CalleeCode += " " + GeneratedCode[j].second + "\n";
1781 for (int j = LastPred+1; j < CodeSize; ++j)
1782 GeneratedCode.pop_back();
1783 CalleeCode += "}\n";
1785 // Uniquing the emission routines.
1786 unsigned EmitFuncNum;
1787 std::map<std::string, unsigned>::iterator EFI =
1788 EmitFunctions.find(CalleeCode);
1789 if (EFI != EmitFunctions.end()) {
1790 EmitFuncNum = EFI->second;
1792 EmitFuncNum = EmitFunctions.size();
1793 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1794 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1797 // Replace the emission code within selection routines with calls to the
1798 // emission functions.
1799 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1800 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1804 std::string OpVTStr;
1805 if (OpVT == MVT::iPTR) {
1807 } else if (OpVT == MVT::iPTRAny) {
1808 OpVTStr = "_iPTRAny";
1809 } else if (OpVT == MVT::isVoid) {
1810 // Nodes with a void result actually have a first result type of either
1811 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1812 // void to this case, we handle it specially here.
1814 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1816 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1817 OpcodeVTMap.find(OpName);
1818 if (OpVTI == OpcodeVTMap.end()) {
1819 std::vector<std::string> VTSet;
1820 VTSet.push_back(OpVTStr);
1821 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1823 OpVTI->second.push_back(OpVTStr);
1825 OS << "SDNode *Select_" << getLegalCName(OpName)
1826 << OpVTStr << "(const SDValue &N) {\n";
1828 // Loop through and reverse all of the CodeList vectors, as we will be
1829 // accessing them from their logical front, but accessing the end of a
1830 // vector is more efficient.
1831 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1832 CodeList &GeneratedCode = CodeForPatterns[i].second;
1833 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1836 // Next, reverse the list of patterns itself for the same reason.
1837 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1839 // Emit all of the patterns now, grouped together to share code.
1840 EmitPatterns(CodeForPatterns, 2, OS);
1842 // If the last pattern has predicates (which could fail) emit code to
1843 // catch the case where nothing handles a pattern.
1844 if (mightNotMatch) {
1845 OS << " cerr << \"Cannot yet select: \";\n";
1846 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1847 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1848 OpName != "ISD::INTRINSIC_VOID") {
1849 OS << " N.Val->dump(CurDAG);\n";
1851 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1852 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1853 << " cerr << \"intrinsic %\"<< "
1854 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1856 OS << " cerr << '\\n';\n"
1858 << " return NULL;\n";
1864 // Emit boilerplate.
1865 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1866 << " std::vector<SDValue> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1867 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1869 << " // Ensure that the asm operands are themselves selected.\n"
1870 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1871 << " AddToISelQueue(Ops[j]);\n\n"
1873 << " std::vector<MVT> VTs;\n"
1874 << " VTs.push_back(MVT::Other);\n"
1875 << " VTs.push_back(MVT::Flag);\n"
1876 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1878 << " return New.Val;\n"
1881 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1882 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::IMPLICIT_DEF,\n"
1883 << " N.getValueType());\n"
1886 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1887 << " SDValue Chain = N.getOperand(0);\n"
1888 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1889 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1890 << " AddToISelQueue(Chain);\n"
1891 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DBG_LABEL,\n"
1892 << " MVT::Other, Tmp, Chain);\n"
1895 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1896 << " SDValue Chain = N.getOperand(0);\n"
1897 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1898 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1899 << " AddToISelQueue(Chain);\n"
1900 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EH_LABEL,\n"
1901 << " MVT::Other, Tmp, Chain);\n"
1904 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1905 << " SDValue Chain = N.getOperand(0);\n"
1906 << " SDValue N1 = N.getOperand(1);\n"
1907 << " SDValue N2 = N.getOperand(2);\n"
1908 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1909 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1910 << " N.Val->dump(CurDAG);\n"
1913 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1914 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1915 << " SDValue Tmp1 = "
1916 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1917 << " SDValue Tmp2 = "
1918 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1919 << " AddToISelQueue(Chain);\n"
1920 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DECLARE,\n"
1921 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
1924 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1925 << " SDValue N0 = N.getOperand(0);\n"
1926 << " SDValue N1 = N.getOperand(1);\n"
1927 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1928 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1929 << " AddToISelQueue(N0);\n"
1930 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EXTRACT_SUBREG,\n"
1931 << " N.getValueType(), N0, Tmp);\n"
1934 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1935 << " SDValue N0 = N.getOperand(0);\n"
1936 << " SDValue N1 = N.getOperand(1);\n"
1937 << " SDValue N2 = N.getOperand(2);\n"
1938 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1939 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1940 << " AddToISelQueue(N1);\n"
1941 << " AddToISelQueue(N0);\n"
1942 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::INSERT_SUBREG,\n"
1943 << " N.getValueType(), N0, N1, Tmp);\n"
1946 OS << "// The main instruction selector code.\n"
1947 << "SDNode *SelectCode(SDValue N) {\n"
1948 << " if (N.isMachineOpcode()) {\n"
1949 << " return NULL; // Already selected.\n"
1951 << " MVT::SimpleValueType NVT = N.Val->getValueType(0).getSimpleVT();\n"
1952 << " switch (N.getOpcode()) {\n"
1953 << " default: break;\n"
1954 << " case ISD::EntryToken: // These leaves remain the same.\n"
1955 << " case ISD::BasicBlock:\n"
1956 << " case ISD::Register:\n"
1957 << " case ISD::HANDLENODE:\n"
1958 << " case ISD::TargetConstant:\n"
1959 << " case ISD::TargetConstantFP:\n"
1960 << " case ISD::TargetConstantPool:\n"
1961 << " case ISD::TargetFrameIndex:\n"
1962 << " case ISD::TargetExternalSymbol:\n"
1963 << " case ISD::TargetJumpTable:\n"
1964 << " case ISD::TargetGlobalTLSAddress:\n"
1965 << " case ISD::TargetGlobalAddress: {\n"
1966 << " return NULL;\n"
1968 << " case ISD::AssertSext:\n"
1969 << " case ISD::AssertZext: {\n"
1970 << " AddToISelQueue(N.getOperand(0));\n"
1971 << " ReplaceUses(N, N.getOperand(0));\n"
1972 << " return NULL;\n"
1974 << " case ISD::TokenFactor:\n"
1975 << " case ISD::CopyFromReg:\n"
1976 << " case ISD::CopyToReg: {\n"
1977 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1978 << " AddToISelQueue(N.getOperand(i));\n"
1979 << " return NULL;\n"
1981 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1982 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1983 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1984 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
1985 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1986 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1987 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1990 // Loop over all of the case statements, emiting a call to each method we
1992 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1993 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1994 PBOI != E; ++PBOI) {
1995 const std::string &OpName = PBOI->first;
1996 // Potentially multiple versions of select for this opcode. One for each
1997 // ValueType of the node (or its first true operand if it doesn't produce a
1999 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2000 OpcodeVTMap.find(OpName);
2001 std::vector<std::string> &OpVTs = OpVTI->second;
2002 OS << " case " << OpName << ": {\n";
2003 // Keep track of whether we see a pattern that has an iPtr result.
2004 bool HasPtrPattern = false;
2005 bool HasDefaultPattern = false;
2007 OS << " switch (NVT) {\n";
2008 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2009 std::string &VTStr = OpVTs[i];
2010 if (VTStr.empty()) {
2011 HasDefaultPattern = true;
2015 // If this is a match on iPTR: don't emit it directly, we need special
2017 if (VTStr == "_iPTR") {
2018 HasPtrPattern = true;
2021 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2022 << " return Select_" << getLegalCName(OpName)
2023 << VTStr << "(N);\n";
2025 OS << " default:\n";
2027 // If there is an iPTR result version of this pattern, emit it here.
2028 if (HasPtrPattern) {
2029 OS << " if (TLI.getPointerTy() == NVT)\n";
2030 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2032 if (HasDefaultPattern) {
2033 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2041 OS << " } // end of big switch.\n\n"
2042 << " cerr << \"Cannot yet select: \";\n"
2043 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2044 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2045 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2046 << " N.Val->dump(CurDAG);\n"
2048 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2049 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
2050 << " cerr << \"intrinsic %\"<< "
2051 "Intrinsic::getName((Intrinsic::ID)iid);\n"
2053 << " cerr << '\\n';\n"
2055 << " return NULL;\n"
2059 void DAGISelEmitter::run(std::ostream &OS) {
2060 EmitSourceFileHeader("DAG Instruction Selector for the " +
2061 CGP.getTargetInfo().getName() + " target", OS);
2063 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2064 << "// *** instruction selector class. These functions are really "
2067 OS << "// Include standard, target-independent definitions and methods used\n"
2068 << "// by the instruction selector.\n";
2069 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
2071 EmitNodeTransforms(OS);
2072 EmitPredicateFunctions(OS);
2074 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2075 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2077 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2078 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2082 // At this point, we have full information about the 'Patterns' we need to
2083 // parse, both implicitly from instructions as well as from explicit pattern
2084 // definitions. Emit the resultant instruction selector.
2085 EmitInstructionSelector(OS);