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->getPredicateFns().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->getPredicateFns().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 typedef std::pair<unsigned, std::string> CodeLine;
144 typedef std::vector<CodeLine> CodeList;
145 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
147 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
148 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
149 const PatternToMatch *LHS = LHSPair.first;
150 const PatternToMatch *RHS = RHSPair.first;
152 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
153 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
154 LHSSize += LHS->getAddedComplexity();
155 RHSSize += RHS->getAddedComplexity();
156 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
157 if (LHSSize < RHSSize) return false;
159 // If the patterns have equal complexity, compare generated instruction cost
160 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
161 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
162 if (LHSCost < RHSCost) return true;
163 if (LHSCost > RHSCost) return false;
165 return getResultPatternSize(LHS->getDstPattern(), CGP) <
166 getResultPatternSize(RHS->getDstPattern(), CGP);
170 /// getRegisterValueType - Look up and return the first ValueType of specified
171 /// RegisterClass record
172 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
173 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
174 return RC->getValueTypeNum(0);
179 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
180 /// type information from it.
181 static void RemoveAllTypes(TreePatternNode *N) {
184 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
185 RemoveAllTypes(N->getChild(i));
188 /// NodeHasProperty - return true if TreePatternNode has the specified
190 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
191 CodeGenDAGPatterns &CGP) {
193 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
195 return CP->hasProperty(Property);
198 Record *Operator = N->getOperator();
199 if (!Operator->isSubClassOf("SDNode")) return false;
201 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
204 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
205 CodeGenDAGPatterns &CGP) {
206 if (NodeHasProperty(N, Property, CGP))
209 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
210 TreePatternNode *Child = N->getChild(i);
211 if (PatternHasProperty(Child, Property, CGP))
218 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
219 return CGP.getSDNodeInfo(Op).getEnumName();
223 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
224 bool isStore = !N->isLeaf() &&
225 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
226 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
229 bool HasChain = false;
230 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
231 TreePatternNode *Child = N->getChild(i);
232 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
240 //===----------------------------------------------------------------------===//
241 // Node Transformation emitter implementation.
243 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
244 // Walk the pattern fragments, adding them to a map, which sorts them by
246 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
247 NXsByNameTy NXsByName;
249 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
251 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
253 OS << "\n// Node transformations.\n";
255 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
257 Record *SDNode = I->second.first;
258 std::string Code = I->second.second;
260 if (Code.empty()) continue; // Empty code? Skip it.
262 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
263 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
265 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
267 if (ClassName != "SDNode")
268 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
269 OS << Code << "\n}\n";
273 //===----------------------------------------------------------------------===//
274 // Predicate emitter implementation.
277 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
278 OS << "\n// Predicate functions.\n";
280 // Walk the pattern fragments, adding them to a map, which sorts them by
282 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
283 PFsByNameTy PFsByName;
285 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
287 PFsByName.insert(std::make_pair(I->first->getName(), *I));
290 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
292 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
293 TreePattern *P = I->second.second;
295 // If there is a code init for this fragment, emit the predicate code.
296 std::string Code = PatFragRecord->getValueAsCode("Predicate");
297 if (Code.empty()) continue;
299 if (P->getOnlyTree()->isLeaf())
300 OS << "inline bool Predicate_" << PatFragRecord->getName()
301 << "(SDNode *N) {\n";
303 std::string ClassName =
304 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
305 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
307 OS << "inline bool Predicate_" << PatFragRecord->getName()
308 << "(SDNode *" << C2 << ") {\n";
309 if (ClassName != "SDNode")
310 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
312 OS << Code << "\n}\n";
319 //===----------------------------------------------------------------------===//
320 // PatternCodeEmitter implementation.
322 class PatternCodeEmitter {
324 CodeGenDAGPatterns &CGP;
327 std::string PredicateCheck;
330 // Instruction selector pattern.
331 TreePatternNode *Pattern;
332 // Matched instruction.
333 TreePatternNode *Instruction;
335 // Node to name mapping
336 std::map<std::string, std::string> VariableMap;
337 // Node to operator mapping
338 std::map<std::string, Record*> OperatorMap;
339 // Name of the folded node which produces a flag.
340 std::pair<std::string, unsigned> FoldedFlag;
341 // Names of all the folded nodes which produce chains.
342 std::vector<std::pair<std::string, unsigned> > FoldedChains;
343 // Original input chain(s).
344 std::vector<std::pair<std::string, std::string> > OrigChains;
345 std::set<std::string> Duplicates;
347 /// LSI - Load/Store information.
348 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
349 /// for each memory access. This facilitates the use of AliasAnalysis in
351 std::vector<std::string> LSI;
353 /// GeneratedCode - This is the buffer that we emit code to. The first int
354 /// indicates whether this is an exit predicate (something that should be
355 /// tested, and if true, the match fails) [when 1], or normal code to emit
356 /// [when 0], or initialization code to emit [when 2].
357 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
358 /// GeneratedDecl - This is the set of all SDValue declarations needed for
359 /// the set of patterns for each top-level opcode.
360 std::set<std::string> &GeneratedDecl;
361 /// TargetOpcodes - The target specific opcodes used by the resulting
363 std::vector<std::string> &TargetOpcodes;
364 std::vector<std::string> &TargetVTs;
365 /// OutputIsVariadic - Records whether the instruction output pattern uses
366 /// variable_ops. This requires that the Emit function be passed an
367 /// additional argument to indicate where the input varargs operands
369 bool &OutputIsVariadic;
370 /// NumInputRootOps - Records the number of operands the root node of the
371 /// input pattern has. This information is used in the generated code to
372 /// pass to Emit functions when variable_ops processing is needed.
373 unsigned &NumInputRootOps;
375 std::string ChainName;
380 void emitCheck(const std::string &S) {
382 GeneratedCode.push_back(std::make_pair(1, S));
384 void emitCode(const std::string &S) {
386 GeneratedCode.push_back(std::make_pair(0, S));
388 void emitInit(const std::string &S) {
390 GeneratedCode.push_back(std::make_pair(2, S));
392 void emitDecl(const std::string &S) {
393 assert(!S.empty() && "Invalid declaration");
394 GeneratedDecl.insert(S);
396 void emitOpcode(const std::string &Opc) {
397 TargetOpcodes.push_back(Opc);
400 void emitVT(const std::string &VT) {
401 TargetVTs.push_back(VT);
405 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
406 TreePatternNode *pattern, TreePatternNode *instr,
407 std::vector<std::pair<unsigned, std::string> > &gc,
408 std::set<std::string> &gd,
409 std::vector<std::string> &to,
410 std::vector<std::string> &tv,
413 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
414 GeneratedCode(gc), GeneratedDecl(gd),
415 TargetOpcodes(to), TargetVTs(tv),
416 OutputIsVariadic(oiv), NumInputRootOps(niro),
417 TmpNo(0), OpcNo(0), VTNo(0) {}
419 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
420 /// if the match fails. At this point, we already know that the opcode for N
421 /// matches, and the SDNode for the result has the RootName specified name.
422 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
423 const std::string &RootName, const std::string &ChainSuffix,
426 // Save loads/stores matched by a pattern.
427 if (!N->isLeaf() && N->getName().empty()) {
428 if (NodeHasProperty(N, SDNPMemOperand, CGP))
429 LSI.push_back(RootName);
432 bool isRoot = (P == NULL);
433 // Emit instruction predicates. Each predicate is just a string for now.
435 // Record input varargs info.
436 NumInputRootOps = N->getNumChildren();
438 if (DisablePatternForFastISel(N, CGP))
441 emitCheck(PredicateCheck);
445 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
446 emitCheck("cast<ConstantSDNode>(" + RootName +
447 ")->getSExtValue() == " + itostr(II->getValue()));
449 } else if (!NodeIsComplexPattern(N)) {
450 assert(0 && "Cannot match this as a leaf value!");
455 // If this node has a name associated with it, capture it in VariableMap. If
456 // we already saw this in the pattern, emit code to verify dagness.
457 if (!N->getName().empty()) {
458 std::string &VarMapEntry = VariableMap[N->getName()];
459 if (VarMapEntry.empty()) {
460 VarMapEntry = RootName;
462 // If we get here, this is a second reference to a specific name. Since
463 // we already have checked that the first reference is valid, we don't
464 // have to recursively match it, just check that it's the same as the
465 // previously named thing.
466 emitCheck(VarMapEntry + " == " + RootName);
471 OperatorMap[N->getName()] = N->getOperator();
475 // Emit code to load the child nodes and match their contents recursively.
477 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
478 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
479 bool EmittedUseCheck = false;
484 // Multiple uses of actual result?
485 emitCheck(RootName + ".hasOneUse()");
486 EmittedUseCheck = true;
488 // If the immediate use can somehow reach this node through another
489 // path, then can't fold it either or it will create a cycle.
490 // e.g. In the following diagram, XX can reach ld through YY. If
491 // ld is folded into XX, then YY is both a predecessor and a successor
501 bool NeedCheck = P != Pattern;
503 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
505 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
506 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
507 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
508 PInfo.getNumOperands() > 1 ||
509 PInfo.hasProperty(SDNPHasChain) ||
510 PInfo.hasProperty(SDNPInFlag) ||
511 PInfo.hasProperty(SDNPOptInFlag);
515 std::string ParentName(RootName.begin(), RootName.end()-1);
516 emitCheck("CanBeFoldedBy(" + RootName + ".getNode(), " + ParentName +
517 ".getNode(), N.getNode())");
524 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
525 "IsChainCompatible(" + ChainName + ".getNode(), " +
526 RootName + ".getNode()))");
527 OrigChains.push_back(std::make_pair(ChainName, RootName));
530 ChainName = "Chain" + ChainSuffix;
531 emitInit("SDValue " + ChainName + " = " + RootName +
536 // Don't fold any node which reads or writes a flag and has multiple uses.
537 // FIXME: We really need to separate the concepts of flag and "glue". Those
538 // real flag results, e.g. X86CMP output, can have multiple uses.
539 // FIXME: If the optional incoming flag does not exist. Then it is ok to
542 (PatternHasProperty(N, SDNPInFlag, CGP) ||
543 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
544 PatternHasProperty(N, SDNPOutFlag, CGP))) {
545 if (!EmittedUseCheck) {
546 // Multiple uses of actual result?
547 emitCheck(RootName + ".hasOneUse()");
551 // If there are node predicates for this, emit the calls.
552 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
553 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
555 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
556 // a constant without a predicate fn that has more that one bit set, handle
557 // this as a special case. This is usually for targets that have special
558 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
559 // handling stuff). Using these instructions is often far more efficient
560 // than materializing the constant. Unfortunately, both the instcombiner
561 // and the dag combiner can often infer that bits are dead, and thus drop
562 // them from the mask in the dag. For example, it might turn 'AND X, 255'
563 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
566 (N->getOperator()->getName() == "and" ||
567 N->getOperator()->getName() == "or") &&
568 N->getChild(1)->isLeaf() &&
569 N->getChild(1)->getPredicateFns().empty()) {
570 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
571 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
572 emitInit("SDValue " + RootName + "0" + " = " +
573 RootName + ".getOperand(" + utostr(0) + ");");
574 emitInit("SDValue " + RootName + "1" + " = " +
575 RootName + ".getOperand(" + utostr(1) + ");");
577 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
578 const char *MaskPredicate = N->getOperator()->getName() == "or"
579 ? "CheckOrMask(" : "CheckAndMask(";
580 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
581 RootName + "1), " + itostr(II->getValue()) + ")");
583 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
584 ChainSuffix + utostr(0), FoundChain);
590 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
591 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
592 RootName + ".getOperand(" +utostr(OpNo) + ");");
594 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
595 ChainSuffix + utostr(OpNo), FoundChain);
598 // Handle cases when root is a complex pattern.
599 const ComplexPattern *CP;
600 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
601 std::string Fn = CP->getSelectFunc();
602 unsigned NumOps = CP->getNumOperands();
603 for (unsigned i = 0; i < NumOps; ++i) {
604 emitDecl("CPTmp" + utostr(i));
605 emitCode("SDValue CPTmp" + utostr(i) + ";");
607 if (CP->hasProperty(SDNPHasChain)) {
608 emitDecl("CPInChain");
609 emitDecl("Chain" + ChainSuffix);
610 emitCode("SDValue CPInChain;");
611 emitCode("SDValue Chain" + ChainSuffix + ";");
614 std::string Code = Fn + "(" + RootName + ", " + RootName;
615 for (unsigned i = 0; i < NumOps; i++)
616 Code += ", CPTmp" + utostr(i);
617 if (CP->hasProperty(SDNPHasChain)) {
618 ChainName = "Chain" + ChainSuffix;
619 Code += ", CPInChain, Chain" + ChainSuffix;
621 emitCheck(Code + ")");
625 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
626 const std::string &RootName,
627 const std::string &ParentRootName,
628 const std::string &ChainSuffix, bool &FoundChain) {
629 if (!Child->isLeaf()) {
630 // If it's not a leaf, recursively match.
631 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
632 emitCheck(RootName + ".getOpcode() == " +
633 CInfo.getEnumName());
634 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
635 bool HasChain = false;
636 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
638 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
640 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
641 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
642 "Pattern folded multiple nodes which produce flags?");
643 FoldedFlag = std::make_pair(RootName,
644 CInfo.getNumResults() + (unsigned)HasChain);
647 // If this child has a name associated with it, capture it in VarMap. If
648 // we already saw this in the pattern, emit code to verify dagness.
649 if (!Child->getName().empty()) {
650 std::string &VarMapEntry = VariableMap[Child->getName()];
651 if (VarMapEntry.empty()) {
652 VarMapEntry = RootName;
654 // If we get here, this is a second reference to a specific name.
655 // Since we already have checked that the first reference is valid,
656 // we don't have to recursively match it, just check that it's the
657 // same as the previously named thing.
658 emitCheck(VarMapEntry + " == " + RootName);
659 Duplicates.insert(RootName);
664 // Handle leaves of various types.
665 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
666 Record *LeafRec = DI->getDef();
667 if (LeafRec->isSubClassOf("RegisterClass") ||
668 LeafRec->getName() == "ptr_rc") {
669 // Handle register references. Nothing to do here.
670 } else if (LeafRec->isSubClassOf("Register")) {
671 // Handle register references.
672 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
673 // Handle complex pattern.
674 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
675 std::string Fn = CP->getSelectFunc();
676 unsigned NumOps = CP->getNumOperands();
677 for (unsigned i = 0; i < NumOps; ++i) {
678 emitDecl("CPTmp" + utostr(i));
679 emitCode("SDValue CPTmp" + utostr(i) + ";");
681 if (CP->hasProperty(SDNPHasChain)) {
682 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
683 FoldedChains.push_back(std::make_pair("CPInChain",
684 PInfo.getNumResults()));
685 ChainName = "Chain" + ChainSuffix;
686 emitDecl("CPInChain");
688 emitCode("SDValue CPInChain;");
689 emitCode("SDValue " + ChainName + ";");
692 std::string Code = Fn + "(";
693 if (CP->hasAttribute(CPAttrParentAsRoot)) {
694 Code += ParentRootName + ", ";
698 if (CP->hasProperty(SDNPHasChain)) {
699 std::string ParentName(RootName.begin(), RootName.end()-1);
700 Code += ParentName + ", ";
703 for (unsigned i = 0; i < NumOps; i++)
704 Code += ", CPTmp" + utostr(i);
705 if (CP->hasProperty(SDNPHasChain))
706 Code += ", CPInChain, Chain" + ChainSuffix;
707 emitCheck(Code + ")");
708 } else if (LeafRec->getName() == "srcvalue") {
709 // Place holder for SRCVALUE nodes. Nothing to do here.
710 } else if (LeafRec->isSubClassOf("ValueType")) {
711 // Make sure this is the specified value type.
712 emitCheck("cast<VTSDNode>(" + RootName +
713 ")->getVT() == MVT::" + LeafRec->getName());
714 } else if (LeafRec->isSubClassOf("CondCode")) {
715 // Make sure this is the specified cond code.
716 emitCheck("cast<CondCodeSDNode>(" + RootName +
717 ")->get() == ISD::" + LeafRec->getName());
723 assert(0 && "Unknown leaf type!");
726 // If there are node predicates for this, emit the calls.
727 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
728 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
730 } else if (IntInit *II =
731 dynamic_cast<IntInit*>(Child->getLeafValue())) {
732 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
733 unsigned CTmp = TmpNo++;
734 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
735 RootName + ")->getSExtValue();");
737 emitCheck("CN" + utostr(CTmp) + " == "
738 "INT64_C(" +itostr(II->getValue()) + ")");
743 assert(0 && "Unknown leaf type!");
748 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
749 /// we actually have to build a DAG!
750 std::vector<std::string>
751 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
752 bool InFlagDecled, bool ResNodeDecled,
753 bool LikeLeaf = false, bool isRoot = false) {
754 // List of arguments of getTargetNode() or SelectNodeTo().
755 std::vector<std::string> NodeOps;
756 // This is something selected from the pattern we matched.
757 if (!N->getName().empty()) {
758 const std::string &VarName = N->getName();
759 std::string Val = VariableMap[VarName];
760 bool ModifiedVal = false;
762 cerr << "Variable '" << VarName << " referenced but not defined "
763 << "and not caught earlier!\n";
766 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
767 // Already selected this operand, just return the tmpval.
768 NodeOps.push_back(Val);
772 const ComplexPattern *CP;
773 unsigned ResNo = TmpNo++;
774 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
775 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
776 std::string CastType;
777 std::string TmpVar = "Tmp" + utostr(ResNo);
778 switch (N->getTypeNum(0)) {
780 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
781 << " type as an immediate constant. Aborting\n";
783 case MVT::i1: CastType = "bool"; break;
784 case MVT::i8: CastType = "unsigned char"; break;
785 case MVT::i16: CastType = "unsigned short"; break;
786 case MVT::i32: CastType = "unsigned"; break;
787 case MVT::i64: CastType = "uint64_t"; break;
789 emitCode("SDValue " + TmpVar +
790 " = CurDAG->getTargetConstant(((" + CastType +
791 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
792 getEnumName(N->getTypeNum(0)) + ");");
793 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
794 // value if used multiple times by this pattern result.
797 NodeOps.push_back(Val);
798 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
799 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
800 std::string TmpVar = "Tmp" + utostr(ResNo);
801 emitCode("SDValue " + TmpVar +
802 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
803 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
804 Val + ")->getValueType(0));");
805 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
806 // value if used multiple times by this pattern result.
809 NodeOps.push_back(Val);
810 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
811 Record *Op = OperatorMap[N->getName()];
812 // Transform ExternalSymbol to TargetExternalSymbol
813 if (Op && Op->getName() == "externalsym") {
814 std::string TmpVar = "Tmp"+utostr(ResNo);
815 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
816 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
817 Val + ")->getSymbol(), " +
818 getEnumName(N->getTypeNum(0)) + ");");
819 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
820 // this value if used multiple times by this pattern result.
824 NodeOps.push_back(Val);
825 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
826 || N->getOperator()->getName() == "tglobaltlsaddr")) {
827 Record *Op = OperatorMap[N->getName()];
828 // Transform GlobalAddress to TargetGlobalAddress
829 if (Op && (Op->getName() == "globaladdr" ||
830 Op->getName() == "globaltlsaddr")) {
831 std::string TmpVar = "Tmp" + utostr(ResNo);
832 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
833 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
834 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
836 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
837 // this value if used multiple times by this pattern result.
841 NodeOps.push_back(Val);
842 } else if (!N->isLeaf()
843 && (N->getOperator()->getName() == "texternalsym"
844 || N->getOperator()->getName() == "tconstpool")) {
845 // Do not rewrite the variable name, since we don't generate a new
847 NodeOps.push_back(Val);
848 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
849 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
850 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
851 NodeOps.push_back("CPTmp" + utostr(i));
854 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
855 // node even if it isn't one. Don't select it.
857 emitCode("AddToISelQueue(" + Val + ");");
858 if (isRoot && N->isLeaf()) {
859 emitCode("ReplaceUses(N, " + Val + ");");
860 emitCode("return NULL;");
863 NodeOps.push_back(Val);
867 VariableMap[VarName] = Val;
872 // If this is an explicit register reference, handle it.
873 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
874 unsigned ResNo = TmpNo++;
875 if (DI->getDef()->isSubClassOf("Register")) {
876 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
877 getQualifiedName(DI->getDef()) + ", " +
878 getEnumName(N->getTypeNum(0)) + ");");
879 NodeOps.push_back("Tmp" + utostr(ResNo));
881 } else if (DI->getDef()->getName() == "zero_reg") {
882 emitCode("SDValue Tmp" + utostr(ResNo) +
883 " = CurDAG->getRegister(0, " +
884 getEnumName(N->getTypeNum(0)) + ");");
885 NodeOps.push_back("Tmp" + utostr(ResNo));
888 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
889 unsigned ResNo = TmpNo++;
890 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
891 emitCode("SDValue Tmp" + utostr(ResNo) +
892 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
893 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
894 NodeOps.push_back("Tmp" + utostr(ResNo));
901 assert(0 && "Unknown leaf type!");
905 Record *Op = N->getOperator();
906 if (Op->isSubClassOf("Instruction")) {
907 const CodeGenTarget &CGT = CGP.getTargetInfo();
908 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
909 const DAGInstruction &Inst = CGP.getInstruction(Op);
910 const TreePattern *InstPat = Inst.getPattern();
911 // FIXME: Assume actual pattern comes before "implicit".
912 TreePatternNode *InstPatNode =
913 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
914 : (InstPat ? InstPat->getTree(0) : NULL);
915 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
916 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
918 bool IsVariadic = isRoot && II.isVariadic;
919 // FIXME: fix how we deal with physical register operands.
920 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
921 bool HasImpResults = isRoot && DstRegs.size() > 0;
922 bool NodeHasOptInFlag = isRoot &&
923 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
924 bool NodeHasInFlag = isRoot &&
925 PatternHasProperty(Pattern, SDNPInFlag, CGP);
926 bool NodeHasOutFlag = isRoot &&
927 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
928 bool NodeHasChain = InstPatNode &&
929 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
930 bool InputHasChain = isRoot &&
931 NodeHasProperty(Pattern, SDNPHasChain, CGP);
932 unsigned NumResults = Inst.getNumResults();
933 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
935 // Record output varargs info.
936 OutputIsVariadic = IsVariadic;
938 if (NodeHasOptInFlag) {
939 emitCode("bool HasInFlag = "
940 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
943 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
945 // How many results is this pattern expected to produce?
946 unsigned NumPatResults = 0;
947 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
948 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
949 if (VT != MVT::isVoid && VT != MVT::Flag)
953 if (OrigChains.size() > 0) {
954 // The original input chain is being ignored. If it is not just
955 // pointing to the op that's being folded, we should create a
956 // TokenFactor with it and the chain of the folded op as the new chain.
957 // We could potentially be doing multiple levels of folding, in that
958 // case, the TokenFactor can have more operands.
959 emitCode("SmallVector<SDValue, 8> InChains;");
960 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
961 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
962 OrigChains[i].second + ".getNode()) {");
963 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
964 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
967 emitCode("AddToISelQueue(" + ChainName + ");");
968 emitCode("InChains.push_back(" + ChainName + ");");
969 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
970 "&InChains[0], InChains.size());");
973 // Loop over all of the operands of the instruction pattern, emitting code
974 // to fill them all in. The node 'N' usually has number children equal to
975 // the number of input operands of the instruction. However, in cases
976 // where there are predicate operands for an instruction, we need to fill
977 // in the 'execute always' values. Match up the node operands to the
978 // instruction operands to do this.
979 std::vector<std::string> AllOps;
980 for (unsigned ChildNo = 0, InstOpNo = NumResults;
981 InstOpNo != II.OperandList.size(); ++InstOpNo) {
982 std::vector<std::string> Ops;
984 // Determine what to emit for this operand.
985 Record *OperandNode = II.OperandList[InstOpNo].Rec;
986 if ((OperandNode->isSubClassOf("PredicateOperand") ||
987 OperandNode->isSubClassOf("OptionalDefOperand")) &&
988 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
989 // This is a predicate or optional def operand; emit the
990 // 'default ops' operands.
991 const DAGDefaultOperand &DefaultOp =
992 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
993 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
994 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
995 InFlagDecled, ResNodeDecled);
996 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
999 // Otherwise this is a normal operand or a predicate operand without
1000 // 'execute always'; emit it.
1001 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1002 InFlagDecled, ResNodeDecled);
1003 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1008 // Emit all the chain and CopyToReg stuff.
1009 bool ChainEmitted = NodeHasChain;
1011 emitCode("AddToISelQueue(" + ChainName + ");");
1012 if (NodeHasInFlag || HasImpInputs)
1013 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1014 InFlagDecled, ResNodeDecled, true);
1015 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1016 if (!InFlagDecled) {
1017 emitCode("SDValue InFlag(0, 0);");
1018 InFlagDecled = true;
1020 if (NodeHasOptInFlag) {
1021 emitCode("if (HasInFlag) {");
1022 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1023 emitCode(" AddToISelQueue(InFlag);");
1028 unsigned ResNo = TmpNo++;
1030 unsigned OpsNo = OpcNo;
1031 std::string CodePrefix;
1032 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1033 std::deque<std::string> After;
1034 std::string NodeName;
1036 NodeName = "Tmp" + utostr(ResNo);
1037 CodePrefix = "SDValue " + NodeName + "(";
1039 NodeName = "ResNode";
1040 if (!ResNodeDecled) {
1041 CodePrefix = "SDNode *" + NodeName + " = ";
1042 ResNodeDecled = true;
1044 CodePrefix = NodeName + " = ";
1047 std::string Code = "Opc" + utostr(OpcNo);
1049 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1051 // Output order: results, chain, flags
1053 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1054 Code += ", VT" + utostr(VTNo);
1055 emitVT(getEnumName(N->getTypeNum(0)));
1057 // Add types for implicit results in physical registers, scheduler will
1058 // care of adding copyfromreg nodes.
1059 for (unsigned i = 0; i < NumDstRegs; i++) {
1060 Record *RR = DstRegs[i];
1061 if (RR->isSubClassOf("Register")) {
1062 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1063 Code += ", " + getEnumName(RVT);
1067 Code += ", MVT::Other";
1069 Code += ", MVT::Flag";
1073 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1074 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1077 // Figure out whether any operands at the end of the op list are not
1078 // part of the variable section.
1079 std::string EndAdjust;
1080 if (NodeHasInFlag || HasImpInputs)
1081 EndAdjust = "-1"; // Always has one flag.
1082 else if (NodeHasOptInFlag)
1083 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1085 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1086 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1088 emitCode(" AddToISelQueue(N.getOperand(i));");
1089 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1093 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1095 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1096 std::vector<std::string>::const_iterator mi, mie;
1097 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1098 emitCode("SDValue LSI_" + *mi + " = "
1099 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1100 *mi + ")->getMemOperand());");
1102 emitCode("Ops" + utostr(OpsNo) + ".push_back(LSI_" + *mi + ");");
1104 AllOps.push_back("LSI_" + *mi);
1110 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1112 AllOps.push_back(ChainName);
1116 if (NodeHasInFlag || HasImpInputs)
1117 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1118 else if (NodeHasOptInFlag) {
1119 emitCode("if (HasInFlag)");
1120 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1122 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1124 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1125 AllOps.push_back("InFlag");
1127 unsigned NumOps = AllOps.size();
1129 if (!NodeHasOptInFlag && NumOps < 4) {
1130 for (unsigned i = 0; i != NumOps; ++i)
1131 Code += ", " + AllOps[i];
1133 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1134 for (unsigned i = 0; i != NumOps; ++i) {
1135 OpsCode += AllOps[i];
1139 emitCode(OpsCode + " };");
1140 Code += ", Ops" + utostr(OpsNo) + ", ";
1141 if (NodeHasOptInFlag) {
1142 Code += "HasInFlag ? ";
1143 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1145 Code += utostr(NumOps);
1152 std::vector<std::string> ReplaceFroms;
1153 std::vector<std::string> ReplaceTos;
1155 NodeOps.push_back("Tmp" + utostr(ResNo));
1158 if (NodeHasOutFlag) {
1159 if (!InFlagDecled) {
1160 After.push_back("SDValue InFlag(ResNode, " +
1161 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1163 InFlagDecled = true;
1165 After.push_back("InFlag = SDValue(ResNode, " +
1166 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1170 if (FoldedChains.size() > 0) {
1172 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1173 ReplaceFroms.push_back("SDValue(" +
1174 FoldedChains[j].first + ".getNode(), " +
1175 utostr(FoldedChains[j].second) +
1177 ReplaceTos.push_back("SDValue(ResNode, " +
1178 utostr(NumResults+NumDstRegs) + ")");
1182 if (NodeHasOutFlag) {
1183 if (FoldedFlag.first != "") {
1184 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1185 utostr(FoldedFlag.second) + ")");
1186 ReplaceTos.push_back("InFlag");
1188 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1189 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1190 utostr(NumPatResults + (unsigned)InputHasChain)
1192 ReplaceTos.push_back("InFlag");
1196 if (!ReplaceFroms.empty() && InputHasChain) {
1197 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1198 utostr(NumPatResults) + ")");
1199 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1200 ChainName + ".getResNo()" + ")");
1201 ChainAssignmentNeeded |= NodeHasChain;
1204 // User does not expect the instruction would produce a chain!
1205 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1207 } else if (InputHasChain && !NodeHasChain) {
1208 // One of the inner node produces a chain.
1209 if (NodeHasOutFlag) {
1210 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1211 utostr(NumPatResults+1) +
1213 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1215 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1216 utostr(NumPatResults) + ")");
1217 ReplaceTos.push_back(ChainName);
1221 if (ChainAssignmentNeeded) {
1222 // Remember which op produces the chain.
1223 std::string ChainAssign;
1225 ChainAssign = ChainName + " = SDValue(" + NodeName +
1226 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1228 ChainAssign = ChainName + " = SDValue(" + NodeName +
1229 ", " + utostr(NumResults+NumDstRegs) + ");";
1231 After.push_front(ChainAssign);
1234 if (ReplaceFroms.size() == 1) {
1235 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1236 ReplaceTos[0] + ");");
1237 } else if (!ReplaceFroms.empty()) {
1238 After.push_back("const SDValue Froms[] = {");
1239 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1240 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1241 After.push_back("};");
1242 After.push_back("const SDValue Tos[] = {");
1243 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1244 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1245 After.push_back("};");
1246 After.push_back("ReplaceUses(Froms, Tos, " +
1247 itostr(ReplaceFroms.size()) + ");");
1250 // We prefer to use SelectNodeTo since it avoids allocation when
1251 // possible and it avoids CSE map recalculation for the node's
1252 // users, however it's tricky to use in a non-root context.
1254 // We also don't use if the pattern replacement is being used to
1255 // jettison a chain result, since morphing the node in place
1256 // would leave users of the chain dangling.
1258 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1259 Code = "CurDAG->getTargetNode(" + Code;
1261 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1265 CodePrefix = "return ";
1267 After.push_back("return ResNode;");
1270 emitCode(CodePrefix + Code + ");");
1271 for (unsigned i = 0, e = After.size(); i != e; ++i)
1276 if (Op->isSubClassOf("SDNodeXForm")) {
1277 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1278 // PatLeaf node - the operand may or may not be a leaf node. But it should
1280 std::vector<std::string> Ops =
1281 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1282 ResNodeDecled, true);
1283 unsigned ResNo = TmpNo++;
1284 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1285 + "(" + Ops.back() + ".getNode());");
1286 NodeOps.push_back("Tmp" + utostr(ResNo));
1288 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1294 throw std::string("Unknown node in result pattern!");
1297 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1298 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1299 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1300 /// for, this returns true otherwise false if Pat has all types.
1301 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1302 const std::string &Prefix, bool isRoot = false) {
1304 if (Pat->getExtTypes() != Other->getExtTypes()) {
1305 // Move a type over from 'other' to 'pat'.
1306 Pat->setTypes(Other->getExtTypes());
1307 // The top level node type is checked outside of the select function.
1309 emitCheck(Prefix + ".getNode()->getValueType(0) == " +
1310 getName(Pat->getTypeNum(0)));
1315 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1316 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1317 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1318 Prefix + utostr(OpNo)))
1324 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1326 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1327 bool &ChainEmitted, bool &InFlagDecled,
1328 bool &ResNodeDecled, bool isRoot = false) {
1329 const CodeGenTarget &T = CGP.getTargetInfo();
1331 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1332 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1333 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1334 TreePatternNode *Child = N->getChild(i);
1335 if (!Child->isLeaf()) {
1336 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1337 InFlagDecled, ResNodeDecled);
1339 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1340 if (!Child->getName().empty()) {
1341 std::string Name = RootName + utostr(OpNo);
1342 if (Duplicates.find(Name) != Duplicates.end())
1343 // A duplicate! Do not emit a copy for this node.
1347 Record *RR = DI->getDef();
1348 if (RR->isSubClassOf("Register")) {
1349 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1350 if (RVT == MVT::Flag) {
1351 if (!InFlagDecled) {
1352 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1353 InFlagDecled = true;
1355 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1356 emitCode("AddToISelQueue(InFlag);");
1358 if (!ChainEmitted) {
1359 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1360 ChainName = "Chain";
1361 ChainEmitted = true;
1363 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1364 if (!InFlagDecled) {
1365 emitCode("SDValue InFlag(0, 0);");
1366 InFlagDecled = true;
1368 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1369 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1370 ", " + getQualifiedName(RR) +
1371 ", " + RootName + utostr(OpNo) + ", InFlag).getNode();");
1372 ResNodeDecled = true;
1373 emitCode(ChainName + " = SDValue(ResNode, 0);");
1374 emitCode("InFlag = SDValue(ResNode, 1);");
1382 if (!InFlagDecled) {
1383 emitCode("SDValue InFlag = " + RootName +
1384 ".getOperand(" + utostr(OpNo) + ");");
1385 InFlagDecled = true;
1387 emitCode("InFlag = " + RootName +
1388 ".getOperand(" + utostr(OpNo) + ");");
1389 emitCode("AddToISelQueue(InFlag);");
1394 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1395 /// stream to match the pattern, and generate the code for the match if it
1396 /// succeeds. Returns true if the pattern is not guaranteed to match.
1397 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1398 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1399 std::set<std::string> &GeneratedDecl,
1400 std::vector<std::string> &TargetOpcodes,
1401 std::vector<std::string> &TargetVTs,
1402 bool &OutputIsVariadic,
1403 unsigned &NumInputRootOps) {
1404 OutputIsVariadic = false;
1405 NumInputRootOps = 0;
1407 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1408 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1409 GeneratedCode, GeneratedDecl,
1410 TargetOpcodes, TargetVTs,
1411 OutputIsVariadic, NumInputRootOps);
1413 // Emit the matcher, capturing named arguments in VariableMap.
1414 bool FoundChain = false;
1415 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1417 // TP - Get *SOME* tree pattern, we don't care which.
1418 TreePattern &TP = *CGP.pf_begin()->second;
1420 // At this point, we know that we structurally match the pattern, but the
1421 // types of the nodes may not match. Figure out the fewest number of type
1422 // comparisons we need to emit. For example, if there is only one integer
1423 // type supported by a target, there should be no type comparisons at all for
1424 // integer patterns!
1426 // To figure out the fewest number of type checks needed, clone the pattern,
1427 // remove the types, then perform type inference on the pattern as a whole.
1428 // If there are unresolved types, emit an explicit check for those types,
1429 // apply the type to the tree, then rerun type inference. Iterate until all
1430 // types are resolved.
1432 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1433 RemoveAllTypes(Pat);
1436 // Resolve/propagate as many types as possible.
1438 bool MadeChange = true;
1440 MadeChange = Pat->ApplyTypeConstraints(TP,
1441 true/*Ignore reg constraints*/);
1443 assert(0 && "Error: could not find consistent types for something we"
1444 " already decided was ok!");
1448 // Insert a check for an unresolved type and add it to the tree. If we find
1449 // an unresolved type to add a check for, this returns true and we iterate,
1450 // otherwise we are done.
1451 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1453 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1454 false, false, false, true);
1458 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1459 /// a line causes any of them to be empty, remove them and return true when
1461 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1462 std::vector<std::pair<unsigned, std::string> > > >
1464 bool ErasedPatterns = false;
1465 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1466 Patterns[i].second.pop_back();
1467 if (Patterns[i].second.empty()) {
1468 Patterns.erase(Patterns.begin()+i);
1470 ErasedPatterns = true;
1473 return ErasedPatterns;
1476 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1477 /// code together between the patterns.
1478 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1479 std::vector<std::pair<unsigned, std::string> > > >
1480 &Patterns, unsigned Indent,
1482 typedef std::pair<unsigned, std::string> CodeLine;
1483 typedef std::vector<CodeLine> CodeList;
1484 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1486 if (Patterns.empty()) return;
1488 // Figure out how many patterns share the next code line. Explicitly copy
1489 // FirstCodeLine so that we don't invalidate a reference when changing
1491 const CodeLine FirstCodeLine = Patterns.back().second.back();
1492 unsigned LastMatch = Patterns.size()-1;
1493 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1496 // If not all patterns share this line, split the list into two pieces. The
1497 // first chunk will use this line, the second chunk won't.
1498 if (LastMatch != 0) {
1499 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1500 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1502 // FIXME: Emit braces?
1503 if (Shared.size() == 1) {
1504 const PatternToMatch &Pattern = *Shared.back().first;
1505 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1506 Pattern.getSrcPattern()->print(OS);
1507 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1508 Pattern.getDstPattern()->print(OS);
1510 unsigned AddedComplexity = Pattern.getAddedComplexity();
1511 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1512 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1514 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1516 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1518 if (FirstCodeLine.first != 1) {
1519 OS << std::string(Indent, ' ') << "{\n";
1522 EmitPatterns(Shared, Indent, OS);
1523 if (FirstCodeLine.first != 1) {
1525 OS << std::string(Indent, ' ') << "}\n";
1528 if (Other.size() == 1) {
1529 const PatternToMatch &Pattern = *Other.back().first;
1530 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1531 Pattern.getSrcPattern()->print(OS);
1532 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1533 Pattern.getDstPattern()->print(OS);
1535 unsigned AddedComplexity = Pattern.getAddedComplexity();
1536 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1537 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1539 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1541 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1543 EmitPatterns(Other, Indent, OS);
1547 // Remove this code from all of the patterns that share it.
1548 bool ErasedPatterns = EraseCodeLine(Patterns);
1550 bool isPredicate = FirstCodeLine.first == 1;
1552 // Otherwise, every pattern in the list has this line. Emit it.
1555 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1557 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1559 // If the next code line is another predicate, and if all of the pattern
1560 // in this group share the same next line, emit it inline now. Do this
1561 // until we run out of common predicates.
1562 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1563 // Check that all of fhe patterns in Patterns end with the same predicate.
1564 bool AllEndWithSamePredicate = true;
1565 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1566 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1567 AllEndWithSamePredicate = false;
1570 // If all of the predicates aren't the same, we can't share them.
1571 if (!AllEndWithSamePredicate) break;
1573 // Otherwise we can. Emit it shared now.
1574 OS << " &&\n" << std::string(Indent+4, ' ')
1575 << Patterns.back().second.back().second;
1576 ErasedPatterns = EraseCodeLine(Patterns);
1583 EmitPatterns(Patterns, Indent, OS);
1586 OS << std::string(Indent-2, ' ') << "}\n";
1589 static std::string getLegalCName(std::string OpName) {
1590 std::string::size_type pos = OpName.find("::");
1591 if (pos != std::string::npos)
1592 OpName.replace(pos, 2, "_");
1596 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1597 const CodeGenTarget &Target = CGP.getTargetInfo();
1599 // Get the namespace to insert instructions into.
1600 std::string InstNS = Target.getInstNamespace();
1601 if (!InstNS.empty()) InstNS += "::";
1603 // Group the patterns by their top-level opcodes.
1604 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1605 // All unique target node emission functions.
1606 std::map<std::string, unsigned> EmitFunctions;
1607 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1608 E = CGP.ptm_end(); I != E; ++I) {
1609 const PatternToMatch &Pattern = *I;
1611 TreePatternNode *Node = Pattern.getSrcPattern();
1612 if (!Node->isLeaf()) {
1613 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1614 push_back(&Pattern);
1616 const ComplexPattern *CP;
1617 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1618 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1619 push_back(&Pattern);
1620 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1621 std::vector<Record*> OpNodes = CP->getRootNodes();
1622 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1623 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1624 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1628 cerr << "Unrecognized opcode '";
1630 cerr << "' on tree pattern '";
1631 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1637 // For each opcode, there might be multiple select functions, one per
1638 // ValueType of the node (or its first operand if it doesn't produce a
1639 // non-chain result.
1640 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1642 // Emit one Select_* method for each top-level opcode. We do this instead of
1643 // emitting one giant switch statement to support compilers where this will
1644 // result in the recursive functions taking less stack space.
1645 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1646 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1647 PBOI != E; ++PBOI) {
1648 const std::string &OpName = PBOI->first;
1649 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1650 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1652 // Split them into groups by type.
1653 std::map<MVT::SimpleValueType,
1654 std::vector<const PatternToMatch*> > PatternsByType;
1655 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1656 const PatternToMatch *Pat = PatternsOfOp[i];
1657 TreePatternNode *SrcPat = Pat->getSrcPattern();
1658 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1661 for (std::map<MVT::SimpleValueType,
1662 std::vector<const PatternToMatch*> >::iterator
1663 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1665 MVT::SimpleValueType OpVT = II->first;
1666 std::vector<const PatternToMatch*> &Patterns = II->second;
1667 typedef std::pair<unsigned, std::string> CodeLine;
1668 typedef std::vector<CodeLine> CodeList;
1669 typedef CodeList::iterator CodeListI;
1671 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1672 std::vector<std::vector<std::string> > PatternOpcodes;
1673 std::vector<std::vector<std::string> > PatternVTs;
1674 std::vector<std::set<std::string> > PatternDecls;
1675 std::vector<bool> OutputIsVariadicFlags;
1676 std::vector<unsigned> NumInputRootOpsCounts;
1677 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1678 CodeList GeneratedCode;
1679 std::set<std::string> GeneratedDecl;
1680 std::vector<std::string> TargetOpcodes;
1681 std::vector<std::string> TargetVTs;
1682 bool OutputIsVariadic;
1683 unsigned NumInputRootOps;
1684 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1685 TargetOpcodes, TargetVTs,
1686 OutputIsVariadic, NumInputRootOps);
1687 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1688 PatternDecls.push_back(GeneratedDecl);
1689 PatternOpcodes.push_back(TargetOpcodes);
1690 PatternVTs.push_back(TargetVTs);
1691 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1692 NumInputRootOpsCounts.push_back(NumInputRootOps);
1695 // Factor target node emission code (emitted by EmitResultCode) into
1696 // separate functions. Uniquing and share them among all instruction
1697 // selection routines.
1698 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1699 CodeList &GeneratedCode = CodeForPatterns[i].second;
1700 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1701 std::vector<std::string> &TargetVTs = PatternVTs[i];
1702 std::set<std::string> Decls = PatternDecls[i];
1703 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1704 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1705 std::vector<std::string> AddedInits;
1706 int CodeSize = (int)GeneratedCode.size();
1708 for (int j = CodeSize-1; j >= 0; --j) {
1709 if (LastPred == -1 && GeneratedCode[j].first == 1)
1711 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1712 AddedInits.push_back(GeneratedCode[j].second);
1715 std::string CalleeCode = "(const SDValue &N";
1716 std::string CallerCode = "(N";
1717 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1718 CalleeCode += ", unsigned Opc" + utostr(j);
1719 CallerCode += ", " + TargetOpcodes[j];
1721 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1722 CalleeCode += ", MVT VT" + utostr(j);
1723 CallerCode += ", " + TargetVTs[j];
1725 for (std::set<std::string>::iterator
1726 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1727 std::string Name = *I;
1728 CalleeCode += ", SDValue &" + Name;
1729 CallerCode += ", " + Name;
1732 if (OutputIsVariadic) {
1733 CalleeCode += ", unsigned NumInputRootOps";
1734 CallerCode += ", " + utostr(NumInputRootOps);
1739 // Prevent emission routines from being inlined to reduce selection
1740 // routines stack frame sizes.
1741 CalleeCode += "DISABLE_INLINE ";
1742 CalleeCode += "{\n";
1744 for (std::vector<std::string>::const_reverse_iterator
1745 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1746 CalleeCode += " " + *I + "\n";
1748 for (int j = LastPred+1; j < CodeSize; ++j)
1749 CalleeCode += " " + GeneratedCode[j].second + "\n";
1750 for (int j = LastPred+1; j < CodeSize; ++j)
1751 GeneratedCode.pop_back();
1752 CalleeCode += "}\n";
1754 // Uniquing the emission routines.
1755 unsigned EmitFuncNum;
1756 std::map<std::string, unsigned>::iterator EFI =
1757 EmitFunctions.find(CalleeCode);
1758 if (EFI != EmitFunctions.end()) {
1759 EmitFuncNum = EFI->second;
1761 EmitFuncNum = EmitFunctions.size();
1762 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1763 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1766 // Replace the emission code within selection routines with calls to the
1767 // emission functions.
1768 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1769 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1773 std::string OpVTStr;
1774 if (OpVT == MVT::iPTR) {
1776 } else if (OpVT == MVT::iPTRAny) {
1777 OpVTStr = "_iPTRAny";
1778 } else if (OpVT == MVT::isVoid) {
1779 // Nodes with a void result actually have a first result type of either
1780 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1781 // void to this case, we handle it specially here.
1783 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1785 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1786 OpcodeVTMap.find(OpName);
1787 if (OpVTI == OpcodeVTMap.end()) {
1788 std::vector<std::string> VTSet;
1789 VTSet.push_back(OpVTStr);
1790 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1792 OpVTI->second.push_back(OpVTStr);
1794 OS << "SDNode *Select_" << getLegalCName(OpName)
1795 << OpVTStr << "(const SDValue &N) {\n";
1797 // We want to emit all of the matching code now. However, we want to emit
1798 // the matches in order of minimal cost. Sort the patterns so the least
1799 // cost one is at the start.
1800 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1801 PatternSortingPredicate(CGP));
1803 // Scan the code to see if all of the patterns are reachable and if it is
1804 // possible that the last one might not match.
1805 bool mightNotMatch = true;
1806 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1807 CodeList &GeneratedCode = CodeForPatterns[i].second;
1808 mightNotMatch = false;
1810 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1811 if (GeneratedCode[j].first == 1) { // predicate.
1812 mightNotMatch = true;
1817 // If this pattern definitely matches, and if it isn't the last one, the
1818 // patterns after it CANNOT ever match. Error out.
1819 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1820 cerr << "Pattern '";
1821 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1822 cerr << "' is impossible to select!\n";
1827 // Loop through and reverse all of the CodeList vectors, as we will be
1828 // accessing them from their logical front, but accessing the end of a
1829 // vector is more efficient.
1830 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1831 CodeList &GeneratedCode = CodeForPatterns[i].second;
1832 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1835 // Next, reverse the list of patterns itself for the same reason.
1836 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1838 // Emit all of the patterns now, grouped together to share code.
1839 EmitPatterns(CodeForPatterns, 2, OS);
1841 // If the last pattern has predicates (which could fail) emit code to
1842 // catch the case where nothing handles a pattern.
1843 if (mightNotMatch) {
1845 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1846 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1847 OpName != "ISD::INTRINSIC_VOID")
1848 OS << " CannotYetSelect(N);\n";
1850 OS << " CannotYetSelectIntrinsic(N);\n";
1852 OS << " return NULL;\n";
1858 // Emit boilerplate.
1859 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1860 << " std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());\n"
1861 << " SelectInlineAsmMemoryOperands(Ops);\n\n"
1863 << " // Ensure that the asm operands are themselves selected.\n"
1864 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1865 << " AddToISelQueue(Ops[j]);\n\n"
1867 << " std::vector<MVT> VTs;\n"
1868 << " VTs.push_back(MVT::Other);\n"
1869 << " VTs.push_back(MVT::Flag);\n"
1870 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1872 << " return New.getNode();\n"
1875 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1876 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,\n"
1877 << " N.getValueType());\n"
1880 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1881 << " SDValue Chain = N.getOperand(0);\n"
1882 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1883 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1884 << " AddToISelQueue(Chain);\n"
1885 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,\n"
1886 << " MVT::Other, Tmp, Chain);\n"
1889 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1890 << " SDValue Chain = N.getOperand(0);\n"
1891 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1892 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1893 << " AddToISelQueue(Chain);\n"
1894 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,\n"
1895 << " MVT::Other, Tmp, Chain);\n"
1898 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1899 << " SDValue Chain = N.getOperand(0);\n"
1900 << " SDValue N1 = N.getOperand(1);\n"
1901 << " SDValue N2 = N.getOperand(2);\n"
1902 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1903 << " CannotYetSelect(N);\n"
1905 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1906 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1907 << " SDValue Tmp1 = "
1908 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1909 << " SDValue Tmp2 = "
1910 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1911 << " AddToISelQueue(Chain);\n"
1912 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DECLARE,\n"
1913 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
1916 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1917 << " SDValue N0 = N.getOperand(0);\n"
1918 << " SDValue N1 = N.getOperand(1);\n"
1919 << " unsigned C = cast<ConstantSDNode>(N1)->getZExtValue();\n"
1920 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1921 << " AddToISelQueue(N0);\n"
1922 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EXTRACT_SUBREG,\n"
1923 << " N.getValueType(), N0, Tmp);\n"
1926 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1927 << " SDValue N0 = N.getOperand(0);\n"
1928 << " SDValue N1 = N.getOperand(1);\n"
1929 << " SDValue N2 = N.getOperand(2);\n"
1930 << " unsigned C = cast<ConstantSDNode>(N2)->getZExtValue();\n"
1931 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1932 << " AddToISelQueue(N1);\n"
1933 << " AddToISelQueue(N0);\n"
1934 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::INSERT_SUBREG,\n"
1935 << " N.getValueType(), N0, N1, Tmp);\n"
1938 OS << "// The main instruction selector code.\n"
1939 << "SDNode *SelectCode(SDValue N) {\n"
1940 << " if (N.isMachineOpcode()) {\n"
1941 << " return NULL; // Already selected.\n"
1943 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT();\n"
1944 << " switch (N.getOpcode()) {\n"
1945 << " default: break;\n"
1946 << " case ISD::EntryToken: // These leaves remain the same.\n"
1947 << " case ISD::BasicBlock:\n"
1948 << " case ISD::Register:\n"
1949 << " case ISD::HANDLENODE:\n"
1950 << " case ISD::TargetConstant:\n"
1951 << " case ISD::TargetConstantFP:\n"
1952 << " case ISD::TargetConstantPool:\n"
1953 << " case ISD::TargetFrameIndex:\n"
1954 << " case ISD::TargetExternalSymbol:\n"
1955 << " case ISD::TargetJumpTable:\n"
1956 << " case ISD::TargetGlobalTLSAddress:\n"
1957 << " case ISD::TargetGlobalAddress: {\n"
1958 << " return NULL;\n"
1960 << " case ISD::AssertSext:\n"
1961 << " case ISD::AssertZext: {\n"
1962 << " AddToISelQueue(N.getOperand(0));\n"
1963 << " ReplaceUses(N, N.getOperand(0));\n"
1964 << " return NULL;\n"
1966 << " case ISD::TokenFactor:\n"
1967 << " case ISD::CopyFromReg:\n"
1968 << " case ISD::CopyToReg: {\n"
1969 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1970 << " AddToISelQueue(N.getOperand(i));\n"
1971 << " return NULL;\n"
1973 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1974 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1975 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1976 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
1977 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1978 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1979 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1981 // Loop over all of the case statements, emiting a call to each method we
1983 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1984 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1985 PBOI != E; ++PBOI) {
1986 const std::string &OpName = PBOI->first;
1987 // Potentially multiple versions of select for this opcode. One for each
1988 // ValueType of the node (or its first true operand if it doesn't produce a
1990 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1991 OpcodeVTMap.find(OpName);
1992 std::vector<std::string> &OpVTs = OpVTI->second;
1993 OS << " case " << OpName << ": {\n";
1994 // Keep track of whether we see a pattern that has an iPtr result.
1995 bool HasPtrPattern = false;
1996 bool HasDefaultPattern = false;
1998 OS << " switch (NVT) {\n";
1999 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2000 std::string &VTStr = OpVTs[i];
2001 if (VTStr.empty()) {
2002 HasDefaultPattern = true;
2006 // If this is a match on iPTR: don't emit it directly, we need special
2008 if (VTStr == "_iPTR") {
2009 HasPtrPattern = true;
2012 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2013 << " return Select_" << getLegalCName(OpName)
2014 << VTStr << "(N);\n";
2016 OS << " default:\n";
2018 // If there is an iPTR result version of this pattern, emit it here.
2019 if (HasPtrPattern) {
2020 OS << " if (TLI.getPointerTy() == NVT)\n";
2021 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2023 if (HasDefaultPattern) {
2024 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2032 OS << " } // end of big switch.\n\n"
2033 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2034 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2035 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2036 << " CannotYetSelect(N);\n"
2038 << " CannotYetSelectIntrinsic(N);\n"
2040 << " return NULL;\n"
2043 OS << "void CannotYetSelect(SDValue N) DISABLE_INLINE {\n"
2044 << " cerr << \"Cannot yet select: \";\n"
2045 << " N.getNode()->dump(CurDAG);\n"
2046 << " cerr << '\\n';\n"
2050 OS << "void CannotYetSelectIntrinsic(SDValue N) DISABLE_INLINE {\n"
2051 << " cerr << \"Cannot yet select: \";\n"
2052 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2053 << "N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();\n"
2054 << " cerr << \"intrinsic %\"<< "
2055 << "Intrinsic::getName((Intrinsic::ID)iid);\n"
2056 << " cerr << '\\n';\n"
2061 void DAGISelEmitter::run(std::ostream &OS) {
2062 EmitSourceFileHeader("DAG Instruction Selector for the " +
2063 CGP.getTargetInfo().getName() + " target", OS);
2065 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2066 << "// *** instruction selector class. These functions are really "
2069 OS << "// Include standard, target-independent definitions and methods used\n"
2070 << "// by the instruction selector.\n";
2071 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
2073 EmitNodeTransforms(OS);
2074 EmitPredicateFunctions(OS);
2076 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2077 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2079 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2080 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2084 // At this point, we have full information about the 'Patterns' we need to
2085 // parse, both implicitly from instructions as well as from explicit pattern
2086 // definitions. Emit the resultant instruction selector.
2087 EmitInstructionSelector(OS);