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 /// getNodeName - The top level Select_* functions have an "SDNode* N"
34 /// argument. When expanding the pattern-matching code, the intermediate
35 /// variables have type SDValue. This function provides a uniform way to
36 /// reference the underlying "SDNode *" for both cases.
37 static std::string getNodeName(const std::string &S) {
38 if (S == "N") return S;
39 return S + ".getNode()";
42 /// getNodeValue - Similar to getNodeName, except it provides a uniform
43 /// way to access the SDValue for both cases.
44 static std::string getValueName(const std::string &S) {
45 if (S == "N") return "SDValue(N, 0)";
49 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
51 static bool NodeIsComplexPattern(TreePatternNode *N) {
52 return (N->isLeaf() &&
53 dynamic_cast<DefInit*>(N->getLeafValue()) &&
54 static_cast<DefInit*>(N->getLeafValue())->getDef()->
55 isSubClassOf("ComplexPattern"));
58 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
59 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
60 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
61 CodeGenDAGPatterns &CGP) {
63 dynamic_cast<DefInit*>(N->getLeafValue()) &&
64 static_cast<DefInit*>(N->getLeafValue())->getDef()->
65 isSubClassOf("ComplexPattern")) {
66 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
72 /// getPatternSize - Return the 'size' of this pattern. We want to match large
73 /// patterns before small ones. This is used to determine the size of a
75 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
76 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
77 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
78 P->getExtTypeNum(0) == MVT::isVoid ||
79 P->getExtTypeNum(0) == MVT::Flag ||
80 P->getExtTypeNum(0) == MVT::iPTR ||
81 P->getExtTypeNum(0) == MVT::iPTRAny) &&
82 "Not a valid pattern node to size!");
83 unsigned Size = 3; // The node itself.
84 // If the root node is a ConstantSDNode, increases its size.
85 // e.g. (set R32:$dst, 0).
86 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
89 // FIXME: This is a hack to statically increase the priority of patterns
90 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
91 // Later we can allow complexity / cost for each pattern to be (optionally)
92 // specified. To get best possible pattern match we'll need to dynamically
93 // calculate the complexity of all patterns a dag can potentially map to.
94 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
96 Size += AM->getNumOperands() * 3;
98 // If this node has some predicate function that must match, it adds to the
99 // complexity of this node.
100 if (!P->getPredicateFns().empty())
103 // Count children in the count if they are also nodes.
104 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
105 TreePatternNode *Child = P->getChild(i);
106 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
107 Size += getPatternSize(Child, CGP);
108 else if (Child->isLeaf()) {
109 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
110 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
111 else if (NodeIsComplexPattern(Child))
112 Size += getPatternSize(Child, CGP);
113 else if (!Child->getPredicateFns().empty())
121 /// getResultPatternCost - Compute the number of instructions for this pattern.
122 /// This is a temporary hack. We should really include the instruction
123 /// latencies in this calculation.
124 static unsigned getResultPatternCost(TreePatternNode *P,
125 CodeGenDAGPatterns &CGP) {
126 if (P->isLeaf()) return 0;
129 Record *Op = P->getOperator();
130 if (Op->isSubClassOf("Instruction")) {
132 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
133 if (II.usesCustomInserter)
136 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
137 Cost += getResultPatternCost(P->getChild(i), CGP);
141 /// getResultPatternCodeSize - Compute the code size of instructions for this
143 static unsigned getResultPatternSize(TreePatternNode *P,
144 CodeGenDAGPatterns &CGP) {
145 if (P->isLeaf()) return 0;
148 Record *Op = P->getOperator();
149 if (Op->isSubClassOf("Instruction")) {
150 Cost += Op->getValueAsInt("CodeSize");
152 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
153 Cost += getResultPatternSize(P->getChild(i), CGP);
157 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
158 // In particular, we want to match maximal patterns first and lowest cost within
159 // a particular complexity first.
160 struct PatternSortingPredicate {
161 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
162 CodeGenDAGPatterns &CGP;
164 typedef std::pair<unsigned, std::string> CodeLine;
165 typedef std::vector<CodeLine> CodeList;
166 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
168 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
169 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
170 const PatternToMatch *LHS = LHSPair.first;
171 const PatternToMatch *RHS = RHSPair.first;
173 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
174 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
175 LHSSize += LHS->getAddedComplexity();
176 RHSSize += RHS->getAddedComplexity();
177 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
178 if (LHSSize < RHSSize) return false;
180 // If the patterns have equal complexity, compare generated instruction cost
181 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
182 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
183 if (LHSCost < RHSCost) return true;
184 if (LHSCost > RHSCost) return false;
186 return getResultPatternSize(LHS->getDstPattern(), CGP) <
187 getResultPatternSize(RHS->getDstPattern(), CGP);
191 /// getRegisterValueType - Look up and return the ValueType of the specified
192 /// register. If the register is a member of multiple register classes which
193 /// have different associated types, return MVT::Other.
194 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
195 bool FoundRC = false;
196 MVT::SimpleValueType VT = MVT::Other;
197 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
198 std::vector<CodeGenRegisterClass>::const_iterator RC;
199 std::vector<Record*>::const_iterator Element;
201 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
202 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
203 if (Element != (*RC).Elements.end()) {
206 VT = (*RC).getValueTypeNum(0);
209 if (VT != (*RC).getValueTypeNum(0)) {
210 // Types of the RC's do not agree. Return MVT::Other. The
211 // target is responsible for handling this.
221 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
222 /// type information from it.
223 static void RemoveAllTypes(TreePatternNode *N) {
226 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
227 RemoveAllTypes(N->getChild(i));
230 /// NodeHasProperty - return true if TreePatternNode has the specified
232 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
233 CodeGenDAGPatterns &CGP) {
235 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
237 return CP->hasProperty(Property);
240 Record *Operator = N->getOperator();
241 if (!Operator->isSubClassOf("SDNode")) return false;
243 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
246 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
247 CodeGenDAGPatterns &CGP) {
248 if (NodeHasProperty(N, Property, CGP))
251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
252 TreePatternNode *Child = N->getChild(i);
253 if (PatternHasProperty(Child, Property, CGP))
260 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
261 return CGP.getSDNodeInfo(Op).getEnumName();
265 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
266 bool isStore = !N->isLeaf() &&
267 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
268 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
271 bool HasChain = false;
272 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
273 TreePatternNode *Child = N->getChild(i);
274 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
282 //===----------------------------------------------------------------------===//
283 // Node Transformation emitter implementation.
285 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
286 // Walk the pattern fragments, adding them to a map, which sorts them by
288 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
289 NXsByNameTy NXsByName;
291 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
293 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
295 OS << "\n// Node transformations.\n";
297 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
299 Record *SDNode = I->second.first;
300 std::string Code = I->second.second;
302 if (Code.empty()) continue; // Empty code? Skip it.
304 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
305 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
307 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
309 if (ClassName != "SDNode")
310 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
311 OS << Code << "\n}\n";
315 //===----------------------------------------------------------------------===//
316 // Predicate emitter implementation.
319 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
320 OS << "\n// Predicate functions.\n";
322 // Walk the pattern fragments, adding them to a map, which sorts them by
324 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
325 PFsByNameTy PFsByName;
327 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
329 PFsByName.insert(std::make_pair(I->first->getName(), *I));
332 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
334 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
335 TreePattern *P = I->second.second;
337 // If there is a code init for this fragment, emit the predicate code.
338 std::string Code = PatFragRecord->getValueAsCode("Predicate");
339 if (Code.empty()) continue;
341 if (P->getOnlyTree()->isLeaf())
342 OS << "inline bool Predicate_" << PatFragRecord->getName()
343 << "(SDNode *N) {\n";
345 std::string ClassName =
346 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
347 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
349 OS << "inline bool Predicate_" << PatFragRecord->getName()
350 << "(SDNode *" << C2 << ") {\n";
351 if (ClassName != "SDNode")
352 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
354 OS << Code << "\n}\n";
361 //===----------------------------------------------------------------------===//
362 // PatternCodeEmitter implementation.
364 class PatternCodeEmitter {
366 CodeGenDAGPatterns &CGP;
369 std::string PredicateCheck;
372 // Instruction selector pattern.
373 TreePatternNode *Pattern;
374 // Matched instruction.
375 TreePatternNode *Instruction;
377 // Node to name mapping
378 std::map<std::string, std::string> VariableMap;
379 // Node to operator mapping
380 std::map<std::string, Record*> OperatorMap;
381 // Name of the folded node which produces a flag.
382 std::pair<std::string, unsigned> FoldedFlag;
383 // Names of all the folded nodes which produce chains.
384 std::vector<std::pair<std::string, unsigned> > FoldedChains;
385 // Original input chain(s).
386 std::vector<std::pair<std::string, std::string> > OrigChains;
387 std::set<std::string> Duplicates;
389 /// LSI - Load/Store information.
390 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
391 /// for each memory access. This facilitates the use of AliasAnalysis in
393 std::vector<std::string> LSI;
395 /// GeneratedCode - This is the buffer that we emit code to. The first int
396 /// indicates whether this is an exit predicate (something that should be
397 /// tested, and if true, the match fails) [when 1], or normal code to emit
398 /// [when 0], or initialization code to emit [when 2].
399 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
400 /// GeneratedDecl - This is the set of all SDValue declarations needed for
401 /// the set of patterns for each top-level opcode.
402 std::set<std::string> &GeneratedDecl;
403 /// TargetOpcodes - The target specific opcodes used by the resulting
405 std::vector<std::string> &TargetOpcodes;
406 std::vector<std::string> &TargetVTs;
407 /// OutputIsVariadic - Records whether the instruction output pattern uses
408 /// variable_ops. This requires that the Emit function be passed an
409 /// additional argument to indicate where the input varargs operands
411 bool &OutputIsVariadic;
412 /// NumInputRootOps - Records the number of operands the root node of the
413 /// input pattern has. This information is used in the generated code to
414 /// pass to Emit functions when variable_ops processing is needed.
415 unsigned &NumInputRootOps;
417 std::string ChainName;
422 void emitCheck(const std::string &S) {
424 GeneratedCode.push_back(std::make_pair(1, S));
426 void emitCode(const std::string &S) {
428 GeneratedCode.push_back(std::make_pair(0, S));
430 void emitInit(const std::string &S) {
432 GeneratedCode.push_back(std::make_pair(2, S));
434 void emitDecl(const std::string &S) {
435 assert(!S.empty() && "Invalid declaration");
436 GeneratedDecl.insert(S);
438 void emitOpcode(const std::string &Opc) {
439 TargetOpcodes.push_back(Opc);
442 void emitVT(const std::string &VT) {
443 TargetVTs.push_back(VT);
447 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
448 TreePatternNode *pattern, TreePatternNode *instr,
449 std::vector<std::pair<unsigned, std::string> > &gc,
450 std::set<std::string> &gd,
451 std::vector<std::string> &to,
452 std::vector<std::string> &tv,
455 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
456 GeneratedCode(gc), GeneratedDecl(gd),
457 TargetOpcodes(to), TargetVTs(tv),
458 OutputIsVariadic(oiv), NumInputRootOps(niro),
459 TmpNo(0), OpcNo(0), VTNo(0) {}
461 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
462 /// if the match fails. At this point, we already know that the opcode for N
463 /// matches, and the SDNode for the result has the RootName specified name.
464 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
465 const std::string &RootName, const std::string &ChainSuffix,
468 // Save loads/stores matched by a pattern.
469 if (!N->isLeaf() && N->getName().empty()) {
470 if (NodeHasProperty(N, SDNPMemOperand, CGP))
471 LSI.push_back(getNodeName(RootName));
474 bool isRoot = (P == NULL);
475 // Emit instruction predicates. Each predicate is just a string for now.
477 // Record input varargs info.
478 NumInputRootOps = N->getNumChildren();
480 if (DisablePatternForFastISel(N, CGP))
481 emitCheck("OptLevel != CodeGenOpt::None");
483 emitCheck(PredicateCheck);
487 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
488 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
489 ")->getSExtValue() == INT64_C(" +
490 itostr(II->getValue()) + ")");
492 } else if (!NodeIsComplexPattern(N)) {
493 assert(0 && "Cannot match this as a leaf value!");
498 // If this node has a name associated with it, capture it in VariableMap. If
499 // we already saw this in the pattern, emit code to verify dagness.
500 if (!N->getName().empty()) {
501 std::string &VarMapEntry = VariableMap[N->getName()];
502 if (VarMapEntry.empty()) {
503 VarMapEntry = RootName;
505 // If we get here, this is a second reference to a specific name. Since
506 // we already have checked that the first reference is valid, we don't
507 // have to recursively match it, just check that it's the same as the
508 // previously named thing.
509 emitCheck(VarMapEntry + " == " + RootName);
514 OperatorMap[N->getName()] = N->getOperator();
518 // Emit code to load the child nodes and match their contents recursively.
520 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
521 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
522 bool EmittedUseCheck = false;
527 // Multiple uses of actual result?
528 emitCheck(getValueName(RootName) + ".hasOneUse()");
529 EmittedUseCheck = true;
531 // If the immediate use can somehow reach this node through another
532 // path, then can't fold it either or it will create a cycle.
533 // e.g. In the following diagram, XX can reach ld through YY. If
534 // ld is folded into XX, then YY is both a predecessor and a successor
544 bool NeedCheck = P != Pattern;
546 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
548 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
549 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
550 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
551 PInfo.getNumOperands() > 1 ||
552 PInfo.hasProperty(SDNPHasChain) ||
553 PInfo.hasProperty(SDNPInFlag) ||
554 PInfo.hasProperty(SDNPOptInFlag);
558 std::string ParentName(RootName.begin(), RootName.end()-1);
559 emitCheck("IsLegalAndProfitableToFold(" + getNodeName(RootName) +
560 ", " + getNodeName(ParentName) + ", N)");
567 emitCheck("(" + ChainName + ".getNode() == " +
568 getNodeName(RootName) + " || "
569 "IsChainCompatible(" + ChainName + ".getNode(), " +
570 getNodeName(RootName) + "))");
571 OrigChains.push_back(std::make_pair(ChainName,
572 getValueName(RootName)));
575 ChainName = "Chain" + ChainSuffix;
576 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
581 // Don't fold any node which reads or writes a flag and has multiple uses.
582 // FIXME: We really need to separate the concepts of flag and "glue". Those
583 // real flag results, e.g. X86CMP output, can have multiple uses.
584 // FIXME: If the optional incoming flag does not exist. Then it is ok to
587 (PatternHasProperty(N, SDNPInFlag, CGP) ||
588 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
589 PatternHasProperty(N, SDNPOutFlag, CGP))) {
590 if (!EmittedUseCheck) {
591 // Multiple uses of actual result?
592 emitCheck(getValueName(RootName) + ".hasOneUse()");
596 // If there are node predicates for this, emit the calls.
597 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
598 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
600 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
601 // a constant without a predicate fn that has more that one bit set, handle
602 // this as a special case. This is usually for targets that have special
603 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
604 // handling stuff). Using these instructions is often far more efficient
605 // than materializing the constant. Unfortunately, both the instcombiner
606 // and the dag combiner can often infer that bits are dead, and thus drop
607 // them from the mask in the dag. For example, it might turn 'AND X, 255'
608 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
611 (N->getOperator()->getName() == "and" ||
612 N->getOperator()->getName() == "or") &&
613 N->getChild(1)->isLeaf() &&
614 N->getChild(1)->getPredicateFns().empty()) {
615 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
616 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
617 emitInit("SDValue " + RootName + "0" + " = " +
618 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
619 emitInit("SDValue " + RootName + "1" + " = " +
620 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
622 unsigned NTmp = TmpNo++;
623 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
624 " = dyn_cast<ConstantSDNode>(" +
625 getNodeName(RootName + "1") + ");");
626 emitCheck("Tmp" + utostr(NTmp));
627 const char *MaskPredicate = N->getOperator()->getName() == "or"
628 ? "CheckOrMask(" : "CheckAndMask(";
629 emitCheck(MaskPredicate + getValueName(RootName + "0") +
630 ", Tmp" + utostr(NTmp) +
631 ", INT64_C(" + itostr(II->getValue()) + "))");
633 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
634 ChainSuffix + utostr(0), FoundChain);
640 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
641 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
642 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
644 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
645 ChainSuffix + utostr(OpNo), FoundChain);
648 // Handle cases when root is a complex pattern.
649 const ComplexPattern *CP;
650 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
651 std::string Fn = CP->getSelectFunc();
652 unsigned NumOps = CP->getNumOperands();
653 for (unsigned i = 0; i < NumOps; ++i) {
654 emitDecl("CPTmp" + RootName + "_" + utostr(i));
655 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
657 if (CP->hasProperty(SDNPHasChain)) {
658 emitDecl("CPInChain");
659 emitDecl("Chain" + ChainSuffix);
660 emitCode("SDValue CPInChain;");
661 emitCode("SDValue Chain" + ChainSuffix + ";");
664 std::string Code = Fn + "(" +
665 getNodeName(RootName) + ", " +
666 getValueName(RootName);
667 for (unsigned i = 0; i < NumOps; i++)
668 Code += ", CPTmp" + RootName + "_" + utostr(i);
669 if (CP->hasProperty(SDNPHasChain)) {
670 ChainName = "Chain" + ChainSuffix;
671 Code += ", CPInChain, Chain" + ChainSuffix;
673 emitCheck(Code + ")");
677 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
678 const std::string &RootName,
679 const std::string &ChainSuffix, bool &FoundChain) {
680 if (!Child->isLeaf()) {
681 // If it's not a leaf, recursively match.
682 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
683 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
684 CInfo.getEnumName());
685 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
686 bool HasChain = false;
687 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
689 FoldedChains.push_back(std::make_pair(getValueName(RootName),
690 CInfo.getNumResults()));
692 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
693 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
694 "Pattern folded multiple nodes which produce flags?");
695 FoldedFlag = std::make_pair(getValueName(RootName),
696 CInfo.getNumResults() + (unsigned)HasChain);
699 // If this child has a name associated with it, capture it in VarMap. If
700 // we already saw this in the pattern, emit code to verify dagness.
701 if (!Child->getName().empty()) {
702 std::string &VarMapEntry = VariableMap[Child->getName()];
703 if (VarMapEntry.empty()) {
704 VarMapEntry = getValueName(RootName);
706 // If we get here, this is a second reference to a specific name.
707 // Since we already have checked that the first reference is valid,
708 // we don't have to recursively match it, just check that it's the
709 // same as the previously named thing.
710 emitCheck(VarMapEntry + " == " + getValueName(RootName));
711 Duplicates.insert(getValueName(RootName));
716 // Handle leaves of various types.
717 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
718 Record *LeafRec = DI->getDef();
719 if (LeafRec->isSubClassOf("RegisterClass") ||
720 LeafRec->isSubClassOf("PointerLikeRegClass")) {
721 // Handle register references. Nothing to do here.
722 } else if (LeafRec->isSubClassOf("Register")) {
723 // Handle register references.
724 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
725 // Handle complex pattern.
726 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
727 std::string Fn = CP->getSelectFunc();
728 unsigned NumOps = CP->getNumOperands();
729 for (unsigned i = 0; i < NumOps; ++i) {
730 emitDecl("CPTmp" + RootName + "_" + utostr(i));
731 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
733 if (CP->hasProperty(SDNPHasChain)) {
734 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
735 FoldedChains.push_back(std::make_pair("CPInChain",
736 PInfo.getNumResults()));
737 ChainName = "Chain" + ChainSuffix;
738 emitDecl("CPInChain");
740 emitCode("SDValue CPInChain;");
741 emitCode("SDValue " + ChainName + ";");
744 std::string Code = Fn + "(N, ";
745 if (CP->hasProperty(SDNPHasChain)) {
746 std::string ParentName(RootName.begin(), RootName.end()-1);
747 Code += getValueName(ParentName) + ", ";
749 Code += getValueName(RootName);
750 for (unsigned i = 0; i < NumOps; i++)
751 Code += ", CPTmp" + RootName + "_" + utostr(i);
752 if (CP->hasProperty(SDNPHasChain))
753 Code += ", CPInChain, Chain" + ChainSuffix;
754 emitCheck(Code + ")");
755 } else if (LeafRec->getName() == "srcvalue") {
756 // Place holder for SRCVALUE nodes. Nothing to do here.
757 } else if (LeafRec->isSubClassOf("ValueType")) {
758 // Make sure this is the specified value type.
759 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
760 ")->getVT() == MVT::" + LeafRec->getName());
761 } else if (LeafRec->isSubClassOf("CondCode")) {
762 // Make sure this is the specified cond code.
763 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
764 ")->get() == ISD::" + LeafRec->getName());
770 assert(0 && "Unknown leaf type!");
773 // If there are node predicates for this, emit the calls.
774 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
775 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
777 } else if (IntInit *II =
778 dynamic_cast<IntInit*>(Child->getLeafValue())) {
779 unsigned NTmp = TmpNo++;
780 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
781 " = dyn_cast<ConstantSDNode>("+
782 getNodeName(RootName) + ");");
783 emitCheck("Tmp" + utostr(NTmp));
784 unsigned CTmp = TmpNo++;
785 emitCode("int64_t CN"+ utostr(CTmp) +
786 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
787 emitCheck("CN" + utostr(CTmp) + " == "
788 "INT64_C(" +itostr(II->getValue()) + ")");
793 assert(0 && "Unknown leaf type!");
798 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
799 /// we actually have to build a DAG!
800 std::vector<std::string>
801 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
802 bool InFlagDecled, bool ResNodeDecled,
803 bool LikeLeaf = false, bool isRoot = false) {
804 // List of arguments of getMachineNode() or SelectNodeTo().
805 std::vector<std::string> NodeOps;
806 // This is something selected from the pattern we matched.
807 if (!N->getName().empty()) {
808 const std::string &VarName = N->getName();
809 std::string Val = VariableMap[VarName];
810 bool ModifiedVal = false;
812 errs() << "Variable '" << VarName << " referenced but not defined "
813 << "and not caught earlier!\n";
816 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
817 // Already selected this operand, just return the tmpval.
818 NodeOps.push_back(getValueName(Val));
822 const ComplexPattern *CP;
823 unsigned ResNo = TmpNo++;
824 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
825 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
826 std::string CastType;
827 std::string TmpVar = "Tmp" + utostr(ResNo);
828 switch (N->getTypeNum(0)) {
830 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
831 << " type as an immediate constant. Aborting\n";
833 case MVT::i1: CastType = "bool"; break;
834 case MVT::i8: CastType = "unsigned char"; break;
835 case MVT::i16: CastType = "unsigned short"; break;
836 case MVT::i32: CastType = "unsigned"; break;
837 case MVT::i64: CastType = "uint64_t"; break;
839 emitCode("SDValue " + TmpVar +
840 " = CurDAG->getTargetConstant(((" + CastType +
841 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
842 getEnumName(N->getTypeNum(0)) + ");");
843 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
844 // value if used multiple times by this pattern result.
847 NodeOps.push_back(getValueName(Val));
848 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
849 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
850 std::string TmpVar = "Tmp" + utostr(ResNo);
851 emitCode("SDValue " + TmpVar +
852 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
853 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
854 Val + ")->getValueType(0));");
855 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
856 // value if used multiple times by this pattern result.
859 NodeOps.push_back(getValueName(Val));
860 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
861 Record *Op = OperatorMap[N->getName()];
862 // Transform ExternalSymbol to TargetExternalSymbol
863 if (Op && Op->getName() == "externalsym") {
864 std::string TmpVar = "Tmp"+utostr(ResNo);
865 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
866 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
867 Val + ")->getSymbol(), " +
868 getEnumName(N->getTypeNum(0)) + ");");
869 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
870 // this value if used multiple times by this pattern result.
874 NodeOps.push_back(getValueName(Val));
875 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
876 || N->getOperator()->getName() == "tglobaltlsaddr")) {
877 Record *Op = OperatorMap[N->getName()];
878 // Transform GlobalAddress to TargetGlobalAddress
879 if (Op && (Op->getName() == "globaladdr" ||
880 Op->getName() == "globaltlsaddr")) {
881 std::string TmpVar = "Tmp" + utostr(ResNo);
882 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
883 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
884 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
886 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
887 // this value if used multiple times by this pattern result.
891 NodeOps.push_back(getValueName(Val));
892 } else if (!N->isLeaf()
893 && (N->getOperator()->getName() == "texternalsym"
894 || N->getOperator()->getName() == "tconstpool")) {
895 // Do not rewrite the variable name, since we don't generate a new
897 NodeOps.push_back(getValueName(Val));
898 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
899 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
900 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
903 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
904 // node even if it isn't one. Don't select it.
906 if (isRoot && N->isLeaf()) {
907 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
908 emitCode("return NULL;");
911 NodeOps.push_back(getValueName(Val));
915 VariableMap[VarName] = Val;
920 // If this is an explicit register reference, handle it.
921 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
922 unsigned ResNo = TmpNo++;
923 if (DI->getDef()->isSubClassOf("Register")) {
924 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
925 getQualifiedName(DI->getDef()) + ", " +
926 getEnumName(N->getTypeNum(0)) + ");");
927 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
929 } else if (DI->getDef()->getName() == "zero_reg") {
930 emitCode("SDValue Tmp" + utostr(ResNo) +
931 " = CurDAG->getRegister(0, " +
932 getEnumName(N->getTypeNum(0)) + ");");
933 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
935 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
936 // Handle a reference to a register class. This is used
937 // in COPY_TO_SUBREG instructions.
938 emitCode("SDValue Tmp" + utostr(ResNo) +
939 " = CurDAG->getTargetConstant(" +
940 getQualifiedName(DI->getDef()) + "RegClassID, " +
942 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
945 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
946 unsigned ResNo = TmpNo++;
947 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
948 emitCode("SDValue Tmp" + utostr(ResNo) +
949 " = CurDAG->getTargetConstant(0x" +
950 utohexstr((uint64_t) II->getValue()) +
951 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
952 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
959 assert(0 && "Unknown leaf type!");
963 Record *Op = N->getOperator();
964 if (Op->isSubClassOf("Instruction")) {
965 const CodeGenTarget &CGT = CGP.getTargetInfo();
966 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
967 const DAGInstruction &Inst = CGP.getInstruction(Op);
968 const TreePattern *InstPat = Inst.getPattern();
969 // FIXME: Assume actual pattern comes before "implicit".
970 TreePatternNode *InstPatNode =
971 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
972 : (InstPat ? InstPat->getTree(0) : NULL);
973 if (InstPatNode && !InstPatNode->isLeaf() &&
974 InstPatNode->getOperator()->getName() == "set") {
975 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
977 bool IsVariadic = isRoot && II.isVariadic;
978 // FIXME: fix how we deal with physical register operands.
979 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
980 bool HasImpResults = isRoot && DstRegs.size() > 0;
981 bool NodeHasOptInFlag = isRoot &&
982 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
983 bool NodeHasInFlag = isRoot &&
984 PatternHasProperty(Pattern, SDNPInFlag, CGP);
985 bool NodeHasOutFlag = isRoot &&
986 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
987 bool NodeHasChain = InstPatNode &&
988 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
989 bool InputHasChain = isRoot &&
990 NodeHasProperty(Pattern, SDNPHasChain, CGP);
991 unsigned NumResults = Inst.getNumResults();
992 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
994 // Record output varargs info.
995 OutputIsVariadic = IsVariadic;
997 if (NodeHasOptInFlag) {
998 emitCode("bool HasInFlag = "
999 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1003 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1005 // How many results is this pattern expected to produce?
1006 unsigned NumPatResults = 0;
1007 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1008 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1009 if (VT != MVT::isVoid && VT != MVT::Flag)
1013 if (OrigChains.size() > 0) {
1014 // The original input chain is being ignored. If it is not just
1015 // pointing to the op that's being folded, we should create a
1016 // TokenFactor with it and the chain of the folded op as the new chain.
1017 // We could potentially be doing multiple levels of folding, in that
1018 // case, the TokenFactor can have more operands.
1019 emitCode("SmallVector<SDValue, 8> InChains;");
1020 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1021 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1022 OrigChains[i].second + ".getNode()) {");
1023 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1026 emitCode("InChains.push_back(" + ChainName + ");");
1027 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1028 "N->getDebugLoc(), MVT::Other, "
1029 "&InChains[0], InChains.size());");
1031 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1032 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1036 // Loop over all of the operands of the instruction pattern, emitting code
1037 // to fill them all in. The node 'N' usually has number children equal to
1038 // the number of input operands of the instruction. However, in cases
1039 // where there are predicate operands for an instruction, we need to fill
1040 // in the 'execute always' values. Match up the node operands to the
1041 // instruction operands to do this.
1042 std::vector<std::string> AllOps;
1043 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1044 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1045 std::vector<std::string> Ops;
1047 // Determine what to emit for this operand.
1048 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1049 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1050 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1051 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1052 // This is a predicate or optional def operand; emit the
1053 // 'default ops' operands.
1054 const DAGDefaultOperand &DefaultOp =
1055 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1056 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1057 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1058 InFlagDecled, ResNodeDecled);
1059 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1062 // Otherwise this is a normal operand or a predicate operand without
1063 // 'execute always'; emit it.
1064 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1065 InFlagDecled, ResNodeDecled);
1066 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1071 // Emit all the chain and CopyToReg stuff.
1072 bool ChainEmitted = NodeHasChain;
1073 if (NodeHasInFlag || HasImpInputs)
1074 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1075 InFlagDecled, ResNodeDecled, true);
1076 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1077 if (!InFlagDecled) {
1078 emitCode("SDValue InFlag(0, 0);");
1079 InFlagDecled = true;
1081 if (NodeHasOptInFlag) {
1082 emitCode("if (HasInFlag) {");
1083 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1088 unsigned ResNo = TmpNo++;
1090 unsigned OpsNo = OpcNo;
1091 std::string CodePrefix;
1092 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1093 std::deque<std::string> After;
1094 std::string NodeName;
1096 NodeName = "Tmp" + utostr(ResNo);
1097 CodePrefix = "SDValue " + NodeName + "(";
1099 NodeName = "ResNode";
1100 if (!ResNodeDecled) {
1101 CodePrefix = "SDNode *" + NodeName + " = ";
1102 ResNodeDecled = true;
1104 CodePrefix = NodeName + " = ";
1107 std::string Code = "Opc" + utostr(OpcNo);
1109 if (!isRoot || (InputHasChain && !NodeHasChain))
1110 // For call to "getMachineNode()".
1111 Code += ", N->getDebugLoc()";
1113 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1115 // Output order: results, chain, flags
1117 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1118 Code += ", VT" + utostr(VTNo);
1119 emitVT(getEnumName(N->getTypeNum(0)));
1121 // Add types for implicit results in physical registers, scheduler will
1122 // care of adding copyfromreg nodes.
1123 for (unsigned i = 0; i < NumDstRegs; i++) {
1124 Record *RR = DstRegs[i];
1125 if (RR->isSubClassOf("Register")) {
1126 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1127 Code += ", " + getEnumName(RVT);
1131 Code += ", MVT::Other";
1133 Code += ", MVT::Flag";
1137 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1138 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1141 // Figure out whether any operands at the end of the op list are not
1142 // part of the variable section.
1143 std::string EndAdjust;
1144 if (NodeHasInFlag || HasImpInputs)
1145 EndAdjust = "-1"; // Always has one flag.
1146 else if (NodeHasOptInFlag)
1147 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1149 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1150 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1152 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1156 // Populate MemRefs with entries for each memory accesses covered by
1158 if (isRoot && !LSI.empty()) {
1159 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1160 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1161 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1162 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1163 emitCode(MemRefs + "[" + utostr(i) + "] = "
1164 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1165 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1166 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1172 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1174 AllOps.push_back(ChainName);
1178 if (NodeHasInFlag || HasImpInputs)
1179 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1180 else if (NodeHasOptInFlag) {
1181 emitCode("if (HasInFlag)");
1182 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1184 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1186 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1187 AllOps.push_back("InFlag");
1189 unsigned NumOps = AllOps.size();
1191 if (!NodeHasOptInFlag && NumOps < 4) {
1192 for (unsigned i = 0; i != NumOps; ++i)
1193 Code += ", " + AllOps[i];
1195 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1196 for (unsigned i = 0; i != NumOps; ++i) {
1197 OpsCode += AllOps[i];
1201 emitCode(OpsCode + " };");
1202 Code += ", Ops" + utostr(OpsNo) + ", ";
1203 if (NodeHasOptInFlag) {
1204 Code += "HasInFlag ? ";
1205 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1207 Code += utostr(NumOps);
1214 std::vector<std::string> ReplaceFroms;
1215 std::vector<std::string> ReplaceTos;
1217 NodeOps.push_back("Tmp" + utostr(ResNo));
1220 if (NodeHasOutFlag) {
1221 if (!InFlagDecled) {
1222 After.push_back("SDValue InFlag(ResNode, " +
1223 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1225 InFlagDecled = true;
1227 After.push_back("InFlag = SDValue(ResNode, " +
1228 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1232 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1233 ReplaceFroms.push_back("SDValue(" +
1234 FoldedChains[j].first + ".getNode(), " +
1235 utostr(FoldedChains[j].second) +
1237 ReplaceTos.push_back("SDValue(ResNode, " +
1238 utostr(NumResults+NumDstRegs) + ")");
1241 if (NodeHasOutFlag) {
1242 if (FoldedFlag.first != "") {
1243 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1244 utostr(FoldedFlag.second) + ")");
1245 ReplaceTos.push_back("InFlag");
1247 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1248 ReplaceFroms.push_back("SDValue(N, " +
1249 utostr(NumPatResults + (unsigned)InputHasChain)
1251 ReplaceTos.push_back("InFlag");
1255 if (!ReplaceFroms.empty() && InputHasChain) {
1256 ReplaceFroms.push_back("SDValue(N, " +
1257 utostr(NumPatResults) + ")");
1258 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1259 ChainName + ".getResNo()" + ")");
1260 ChainAssignmentNeeded |= NodeHasChain;
1263 // User does not expect the instruction would produce a chain!
1264 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1266 } else if (InputHasChain && !NodeHasChain) {
1267 // One of the inner node produces a chain.
1268 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1269 ReplaceFroms.push_back("SDValue(N, " +
1270 utostr(NumPatResults) + ")");
1271 ReplaceTos.push_back(ChainName);
1275 if (ChainAssignmentNeeded) {
1276 // Remember which op produces the chain.
1277 std::string ChainAssign;
1279 ChainAssign = ChainName + " = SDValue(" + NodeName +
1280 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1282 ChainAssign = ChainName + " = SDValue(" + NodeName +
1283 ", " + utostr(NumResults+NumDstRegs) + ");";
1285 After.push_front(ChainAssign);
1288 if (ReplaceFroms.size() == 1) {
1289 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1290 ReplaceTos[0] + ");");
1291 } else if (!ReplaceFroms.empty()) {
1292 After.push_back("const SDValue Froms[] = {");
1293 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1294 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1295 After.push_back("};");
1296 After.push_back("const SDValue Tos[] = {");
1297 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1298 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1299 After.push_back("};");
1300 After.push_back("ReplaceUses(Froms, Tos, " +
1301 itostr(ReplaceFroms.size()) + ");");
1304 // We prefer to use SelectNodeTo since it avoids allocation when
1305 // possible and it avoids CSE map recalculation for the node's
1306 // users, however it's tricky to use in a non-root context.
1308 // We also don't use SelectNodeTo if the pattern replacement is being
1309 // used to jettison a chain result, since morphing the node in place
1310 // would leave users of the chain dangling.
1312 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1313 Code = "CurDAG->getMachineNode(" + Code;
1315 Code = "CurDAG->SelectNodeTo(N, " + Code;
1319 CodePrefix = "return ";
1321 After.push_back("return ResNode;");
1324 emitCode(CodePrefix + Code + ");");
1328 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1329 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1332 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1333 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1337 for (unsigned i = 0, e = After.size(); i != e; ++i)
1342 if (Op->isSubClassOf("SDNodeXForm")) {
1343 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1344 // PatLeaf node - the operand may or may not be a leaf node. But it should
1346 std::vector<std::string> Ops =
1347 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1348 ResNodeDecled, true);
1349 unsigned ResNo = TmpNo++;
1350 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1351 + "(" + Ops.back() + ".getNode());");
1352 NodeOps.push_back("Tmp" + utostr(ResNo));
1354 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1360 throw std::string("Unknown node in result pattern!");
1363 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1364 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1365 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1366 /// for, this returns true otherwise false if Pat has all types.
1367 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1368 const std::string &Prefix, bool isRoot = false) {
1370 if (Pat->getExtTypes() != Other->getExtTypes()) {
1371 // Move a type over from 'other' to 'pat'.
1372 Pat->setTypes(Other->getExtTypes());
1373 // The top level node type is checked outside of the select function.
1375 emitCheck(Prefix + ".getValueType() == " +
1376 getName(Pat->getTypeNum(0)));
1381 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1382 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1383 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1384 Prefix + utostr(OpNo)))
1390 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1392 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1393 bool &ChainEmitted, bool &InFlagDecled,
1394 bool &ResNodeDecled, bool isRoot = false) {
1395 const CodeGenTarget &T = CGP.getTargetInfo();
1397 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1398 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1399 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1400 TreePatternNode *Child = N->getChild(i);
1401 if (!Child->isLeaf()) {
1402 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1403 InFlagDecled, ResNodeDecled);
1405 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1406 if (!Child->getName().empty()) {
1407 std::string Name = RootName + utostr(OpNo);
1408 if (Duplicates.find(Name) != Duplicates.end())
1409 // A duplicate! Do not emit a copy for this node.
1413 Record *RR = DI->getDef();
1414 if (RR->isSubClassOf("Register")) {
1415 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1416 if (RVT == MVT::Flag) {
1417 if (!InFlagDecled) {
1418 emitCode("SDValue InFlag = " +
1419 getValueName(RootName + utostr(OpNo)) + ";");
1420 InFlagDecled = true;
1422 emitCode("InFlag = " +
1423 getValueName(RootName + utostr(OpNo)) + ";");
1425 if (!ChainEmitted) {
1426 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1427 ChainName = "Chain";
1428 ChainEmitted = true;
1430 if (!InFlagDecled) {
1431 emitCode("SDValue InFlag(0, 0);");
1432 InFlagDecled = true;
1434 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1435 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1436 ", " + getNodeName(RootName) + "->getDebugLoc()" +
1437 ", " + getQualifiedName(RR) +
1438 ", " + getValueName(RootName + utostr(OpNo)) +
1439 ", InFlag).getNode();");
1440 ResNodeDecled = true;
1441 emitCode(ChainName + " = SDValue(ResNode, 0);");
1442 emitCode("InFlag = SDValue(ResNode, 1);");
1450 if (!InFlagDecled) {
1451 emitCode("SDValue InFlag = " + getNodeName(RootName) +
1452 "->getOperand(" + utostr(OpNo) + ");");
1453 InFlagDecled = true;
1455 emitCode("InFlag = " + getNodeName(RootName) +
1456 "->getOperand(" + utostr(OpNo) + ");");
1461 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1462 /// stream to match the pattern, and generate the code for the match if it
1463 /// succeeds. Returns true if the pattern is not guaranteed to match.
1464 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1465 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1466 std::set<std::string> &GeneratedDecl,
1467 std::vector<std::string> &TargetOpcodes,
1468 std::vector<std::string> &TargetVTs,
1469 bool &OutputIsVariadic,
1470 unsigned &NumInputRootOps) {
1471 OutputIsVariadic = false;
1472 NumInputRootOps = 0;
1474 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1475 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1476 GeneratedCode, GeneratedDecl,
1477 TargetOpcodes, TargetVTs,
1478 OutputIsVariadic, NumInputRootOps);
1480 // Emit the matcher, capturing named arguments in VariableMap.
1481 bool FoundChain = false;
1482 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1484 // TP - Get *SOME* tree pattern, we don't care which.
1485 TreePattern &TP = *CGP.pf_begin()->second;
1487 // At this point, we know that we structurally match the pattern, but the
1488 // types of the nodes may not match. Figure out the fewest number of type
1489 // comparisons we need to emit. For example, if there is only one integer
1490 // type supported by a target, there should be no type comparisons at all for
1491 // integer patterns!
1493 // To figure out the fewest number of type checks needed, clone the pattern,
1494 // remove the types, then perform type inference on the pattern as a whole.
1495 // If there are unresolved types, emit an explicit check for those types,
1496 // apply the type to the tree, then rerun type inference. Iterate until all
1497 // types are resolved.
1499 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1500 RemoveAllTypes(Pat);
1503 // Resolve/propagate as many types as possible.
1505 bool MadeChange = true;
1507 MadeChange = Pat->ApplyTypeConstraints(TP,
1508 true/*Ignore reg constraints*/);
1510 assert(0 && "Error: could not find consistent types for something we"
1511 " already decided was ok!");
1515 // Insert a check for an unresolved type and add it to the tree. If we find
1516 // an unresolved type to add a check for, this returns true and we iterate,
1517 // otherwise we are done.
1518 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1520 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1521 false, false, false, true);
1525 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1526 /// a line causes any of them to be empty, remove them and return true when
1528 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1529 std::vector<std::pair<unsigned, std::string> > > >
1531 bool ErasedPatterns = false;
1532 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1533 Patterns[i].second.pop_back();
1534 if (Patterns[i].second.empty()) {
1535 Patterns.erase(Patterns.begin()+i);
1537 ErasedPatterns = true;
1540 return ErasedPatterns;
1543 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1544 /// code together between the patterns.
1545 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1546 std::vector<std::pair<unsigned, std::string> > > >
1547 &Patterns, unsigned Indent,
1549 typedef std::pair<unsigned, std::string> CodeLine;
1550 typedef std::vector<CodeLine> CodeList;
1551 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1553 if (Patterns.empty()) return;
1555 // Figure out how many patterns share the next code line. Explicitly copy
1556 // FirstCodeLine so that we don't invalidate a reference when changing
1558 const CodeLine FirstCodeLine = Patterns.back().second.back();
1559 unsigned LastMatch = Patterns.size()-1;
1560 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1563 // If not all patterns share this line, split the list into two pieces. The
1564 // first chunk will use this line, the second chunk won't.
1565 if (LastMatch != 0) {
1566 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1567 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1569 // FIXME: Emit braces?
1570 if (Shared.size() == 1) {
1571 const PatternToMatch &Pattern = *Shared.back().first;
1572 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1573 Pattern.getSrcPattern()->print(OS);
1574 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1575 Pattern.getDstPattern()->print(OS);
1577 unsigned AddedComplexity = Pattern.getAddedComplexity();
1578 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1579 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1581 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1583 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1585 if (FirstCodeLine.first != 1) {
1586 OS << std::string(Indent, ' ') << "{\n";
1589 EmitPatterns(Shared, Indent, OS);
1590 if (FirstCodeLine.first != 1) {
1592 OS << std::string(Indent, ' ') << "}\n";
1595 if (Other.size() == 1) {
1596 const PatternToMatch &Pattern = *Other.back().first;
1597 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1598 Pattern.getSrcPattern()->print(OS);
1599 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1600 Pattern.getDstPattern()->print(OS);
1602 unsigned AddedComplexity = Pattern.getAddedComplexity();
1603 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1604 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1606 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1608 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1610 EmitPatterns(Other, Indent, OS);
1614 // Remove this code from all of the patterns that share it.
1615 bool ErasedPatterns = EraseCodeLine(Patterns);
1617 bool isPredicate = FirstCodeLine.first == 1;
1619 // Otherwise, every pattern in the list has this line. Emit it.
1622 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1624 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1626 // If the next code line is another predicate, and if all of the pattern
1627 // in this group share the same next line, emit it inline now. Do this
1628 // until we run out of common predicates.
1629 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1630 // Check that all of the patterns in Patterns end with the same predicate.
1631 bool AllEndWithSamePredicate = true;
1632 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1633 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1634 AllEndWithSamePredicate = false;
1637 // If all of the predicates aren't the same, we can't share them.
1638 if (!AllEndWithSamePredicate) break;
1640 // Otherwise we can. Emit it shared now.
1641 OS << " &&\n" << std::string(Indent+4, ' ')
1642 << Patterns.back().second.back().second;
1643 ErasedPatterns = EraseCodeLine(Patterns);
1650 EmitPatterns(Patterns, Indent, OS);
1653 OS << std::string(Indent-2, ' ') << "}\n";
1656 static std::string getLegalCName(std::string OpName) {
1657 std::string::size_type pos = OpName.find("::");
1658 if (pos != std::string::npos)
1659 OpName.replace(pos, 2, "_");
1663 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1664 const CodeGenTarget &Target = CGP.getTargetInfo();
1666 // Get the namespace to insert instructions into.
1667 std::string InstNS = Target.getInstNamespace();
1668 if (!InstNS.empty()) InstNS += "::";
1670 // Group the patterns by their top-level opcodes.
1671 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1672 // All unique target node emission functions.
1673 std::map<std::string, unsigned> EmitFunctions;
1674 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1675 E = CGP.ptm_end(); I != E; ++I) {
1676 const PatternToMatch &Pattern = *I;
1678 TreePatternNode *Node = Pattern.getSrcPattern();
1679 if (!Node->isLeaf()) {
1680 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1681 push_back(&Pattern);
1683 const ComplexPattern *CP;
1684 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1685 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1686 push_back(&Pattern);
1687 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1688 std::vector<Record*> OpNodes = CP->getRootNodes();
1689 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1690 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1691 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1695 errs() << "Unrecognized opcode '";
1697 errs() << "' on tree pattern '";
1698 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1704 // For each opcode, there might be multiple select functions, one per
1705 // ValueType of the node (or its first operand if it doesn't produce a
1706 // non-chain result.
1707 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1709 // Emit one Select_* method for each top-level opcode. We do this instead of
1710 // emitting one giant switch statement to support compilers where this will
1711 // result in the recursive functions taking less stack space.
1712 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1713 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1714 PBOI != E; ++PBOI) {
1715 const std::string &OpName = PBOI->first;
1716 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1717 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1719 // Split them into groups by type.
1720 std::map<MVT::SimpleValueType,
1721 std::vector<const PatternToMatch*> > PatternsByType;
1722 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1723 const PatternToMatch *Pat = PatternsOfOp[i];
1724 TreePatternNode *SrcPat = Pat->getSrcPattern();
1725 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1728 for (std::map<MVT::SimpleValueType,
1729 std::vector<const PatternToMatch*> >::iterator
1730 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1732 MVT::SimpleValueType OpVT = II->first;
1733 std::vector<const PatternToMatch*> &Patterns = II->second;
1734 typedef std::pair<unsigned, std::string> CodeLine;
1735 typedef std::vector<CodeLine> CodeList;
1736 typedef CodeList::iterator CodeListI;
1738 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1739 std::vector<std::vector<std::string> > PatternOpcodes;
1740 std::vector<std::vector<std::string> > PatternVTs;
1741 std::vector<std::set<std::string> > PatternDecls;
1742 std::vector<bool> OutputIsVariadicFlags;
1743 std::vector<unsigned> NumInputRootOpsCounts;
1744 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1745 CodeList GeneratedCode;
1746 std::set<std::string> GeneratedDecl;
1747 std::vector<std::string> TargetOpcodes;
1748 std::vector<std::string> TargetVTs;
1749 bool OutputIsVariadic;
1750 unsigned NumInputRootOps;
1751 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1752 TargetOpcodes, TargetVTs,
1753 OutputIsVariadic, NumInputRootOps);
1754 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1755 PatternDecls.push_back(GeneratedDecl);
1756 PatternOpcodes.push_back(TargetOpcodes);
1757 PatternVTs.push_back(TargetVTs);
1758 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1759 NumInputRootOpsCounts.push_back(NumInputRootOps);
1762 // Factor target node emission code (emitted by EmitResultCode) into
1763 // separate functions. Uniquing and share them among all instruction
1764 // selection routines.
1765 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1766 CodeList &GeneratedCode = CodeForPatterns[i].second;
1767 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1768 std::vector<std::string> &TargetVTs = PatternVTs[i];
1769 std::set<std::string> Decls = PatternDecls[i];
1770 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1771 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1772 std::vector<std::string> AddedInits;
1773 int CodeSize = (int)GeneratedCode.size();
1775 for (int j = CodeSize-1; j >= 0; --j) {
1776 if (LastPred == -1 && GeneratedCode[j].first == 1)
1778 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1779 AddedInits.push_back(GeneratedCode[j].second);
1782 std::string CalleeCode = "(SDNode *N";
1783 std::string CallerCode = "(N";
1784 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1785 CalleeCode += ", unsigned Opc" + utostr(j);
1786 CallerCode += ", " + TargetOpcodes[j];
1788 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1789 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1790 CallerCode += ", " + TargetVTs[j];
1792 for (std::set<std::string>::iterator
1793 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1794 std::string Name = *I;
1795 CalleeCode += ", SDValue &" + Name;
1796 CallerCode += ", " + Name;
1799 if (OutputIsVariadic) {
1800 CalleeCode += ", unsigned NumInputRootOps";
1801 CallerCode += ", " + utostr(NumInputRootOps);
1805 CalleeCode += ") {\n";
1807 for (std::vector<std::string>::const_reverse_iterator
1808 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1809 CalleeCode += " " + *I + "\n";
1811 for (int j = LastPred+1; j < CodeSize; ++j)
1812 CalleeCode += " " + GeneratedCode[j].second + "\n";
1813 for (int j = LastPred+1; j < CodeSize; ++j)
1814 GeneratedCode.pop_back();
1815 CalleeCode += "}\n";
1817 // Uniquing the emission routines.
1818 unsigned EmitFuncNum;
1819 std::map<std::string, unsigned>::iterator EFI =
1820 EmitFunctions.find(CalleeCode);
1821 if (EFI != EmitFunctions.end()) {
1822 EmitFuncNum = EFI->second;
1824 EmitFuncNum = EmitFunctions.size();
1825 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1826 // Prevent emission routines from being inlined to reduce selection
1827 // routines stack frame sizes.
1828 OS << "DISABLE_INLINE ";
1829 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1832 // Replace the emission code within selection routines with calls to the
1833 // emission functions.
1835 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
1837 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1838 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1840 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1841 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1842 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1843 GeneratedCode.push_back(std::make_pair(0, "}"));
1844 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
1846 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1850 std::string OpVTStr;
1851 if (OpVT == MVT::iPTR) {
1853 } else if (OpVT == MVT::iPTRAny) {
1854 OpVTStr = "_iPTRAny";
1855 } else if (OpVT == MVT::isVoid) {
1856 // Nodes with a void result actually have a first result type of either
1857 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1858 // void to this case, we handle it specially here.
1860 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1862 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1863 OpcodeVTMap.find(OpName);
1864 if (OpVTI == OpcodeVTMap.end()) {
1865 std::vector<std::string> VTSet;
1866 VTSet.push_back(OpVTStr);
1867 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1869 OpVTI->second.push_back(OpVTStr);
1871 // We want to emit all of the matching code now. However, we want to emit
1872 // the matches in order of minimal cost. Sort the patterns so the least
1873 // cost one is at the start.
1874 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1875 PatternSortingPredicate(CGP));
1877 // Scan the code to see if all of the patterns are reachable and if it is
1878 // possible that the last one might not match.
1879 bool mightNotMatch = true;
1880 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1881 CodeList &GeneratedCode = CodeForPatterns[i].second;
1882 mightNotMatch = false;
1884 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1885 if (GeneratedCode[j].first == 1) { // predicate.
1886 mightNotMatch = true;
1891 // If this pattern definitely matches, and if it isn't the last one, the
1892 // patterns after it CANNOT ever match. Error out.
1893 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1894 errs() << "Pattern '";
1895 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1896 errs() << "' is impossible to select!\n";
1901 // Loop through and reverse all of the CodeList vectors, as we will be
1902 // accessing them from their logical front, but accessing the end of a
1903 // vector is more efficient.
1904 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1905 CodeList &GeneratedCode = CodeForPatterns[i].second;
1906 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1909 // Next, reverse the list of patterns itself for the same reason.
1910 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1912 OS << "SDNode *Select_" << getLegalCName(OpName)
1913 << OpVTStr << "(SDNode *N) {\n";
1915 // Emit all of the patterns now, grouped together to share code.
1916 EmitPatterns(CodeForPatterns, 2, OS);
1918 // If the last pattern has predicates (which could fail) emit code to
1919 // catch the case where nothing handles a pattern.
1920 if (mightNotMatch) {
1922 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1923 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1924 OpName != "ISD::INTRINSIC_VOID")
1925 OS << " CannotYetSelect(N);\n";
1927 OS << " CannotYetSelectIntrinsic(N);\n";
1929 OS << " return NULL;\n";
1935 OS << "// The main instruction selector code.\n"
1936 << "SDNode *SelectCode(SDNode *N) {\n"
1937 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1938 << " switch (N->getOpcode()) {\n"
1940 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
1942 << " case ISD::EntryToken: // These nodes remain the same.\n"
1943 << " case ISD::BasicBlock:\n"
1944 << " case ISD::Register:\n"
1945 << " case ISD::HANDLENODE:\n"
1946 << " case ISD::TargetConstant:\n"
1947 << " case ISD::TargetConstantFP:\n"
1948 << " case ISD::TargetConstantPool:\n"
1949 << " case ISD::TargetFrameIndex:\n"
1950 << " case ISD::TargetExternalSymbol:\n"
1951 << " case ISD::TargetBlockAddress:\n"
1952 << " case ISD::TargetJumpTable:\n"
1953 << " case ISD::TargetGlobalTLSAddress:\n"
1954 << " case ISD::TargetGlobalAddress:\n"
1955 << " case ISD::TokenFactor:\n"
1956 << " case ISD::CopyFromReg:\n"
1957 << " case ISD::CopyToReg: {\n"
1958 << " return NULL;\n"
1960 << " case ISD::AssertSext:\n"
1961 << " case ISD::AssertZext: {\n"
1962 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
1963 << " return NULL;\n"
1965 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1966 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1967 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1969 // Loop over all of the case statements, emiting a call to each method we
1971 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1972 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1973 PBOI != E; ++PBOI) {
1974 const std::string &OpName = PBOI->first;
1975 // Potentially multiple versions of select for this opcode. One for each
1976 // ValueType of the node (or its first true operand if it doesn't produce a
1978 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1979 OpcodeVTMap.find(OpName);
1980 std::vector<std::string> &OpVTs = OpVTI->second;
1981 OS << " case " << OpName << ": {\n";
1982 // If we have only one variant and it's the default, elide the
1983 // switch. Marginally faster, and makes MSVC happier.
1984 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1985 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1990 // Keep track of whether we see a pattern that has an iPtr result.
1991 bool HasPtrPattern = false;
1992 bool HasDefaultPattern = false;
1994 OS << " switch (NVT) {\n";
1995 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1996 std::string &VTStr = OpVTs[i];
1997 if (VTStr.empty()) {
1998 HasDefaultPattern = true;
2002 // If this is a match on iPTR: don't emit it directly, we need special
2004 if (VTStr == "_iPTR") {
2005 HasPtrPattern = true;
2008 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2009 << " return Select_" << getLegalCName(OpName)
2010 << VTStr << "(N);\n";
2012 OS << " default:\n";
2014 // If there is an iPTR result version of this pattern, emit it here.
2015 if (HasPtrPattern) {
2016 OS << " if (TLI.getPointerTy() == NVT)\n";
2017 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2019 if (HasDefaultPattern) {
2020 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2028 OS << " } // end of big switch.\n\n"
2029 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2030 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2031 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
2032 << " CannotYetSelect(N);\n"
2034 << " CannotYetSelectIntrinsic(N);\n"
2036 << " return NULL;\n"
2040 void DAGISelEmitter::run(raw_ostream &OS) {
2041 EmitSourceFileHeader("DAG Instruction Selector for the " +
2042 CGP.getTargetInfo().getName() + " target", OS);
2044 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2045 << "// *** instruction selector class. These functions are really "
2048 OS << "// Include standard, target-independent definitions and methods used\n"
2049 << "// by the instruction selector.\n";
2050 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
2052 EmitNodeTransforms(OS);
2053 EmitPredicateFunctions(OS);
2055 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
2056 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2058 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2059 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2060 DEBUG(errs() << "\n");
2063 // At this point, we have full information about the 'Patterns' we need to
2064 // parse, both implicitly from instructions as well as from explicit pattern
2065 // definitions. Emit the resultant instruction selector.
2066 EmitInstructionSelector(OS);