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() == INT64_C(" +
448 itostr(II->getValue()) + ")");
450 } else if (!NodeIsComplexPattern(N)) {
451 assert(0 && "Cannot match this as a leaf value!");
456 // If this node has a name associated with it, capture it in VariableMap. If
457 // we already saw this in the pattern, emit code to verify dagness.
458 if (!N->getName().empty()) {
459 std::string &VarMapEntry = VariableMap[N->getName()];
460 if (VarMapEntry.empty()) {
461 VarMapEntry = RootName;
463 // If we get here, this is a second reference to a specific name. Since
464 // we already have checked that the first reference is valid, we don't
465 // have to recursively match it, just check that it's the same as the
466 // previously named thing.
467 emitCheck(VarMapEntry + " == " + RootName);
472 OperatorMap[N->getName()] = N->getOperator();
476 // Emit code to load the child nodes and match their contents recursively.
478 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
479 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
480 bool EmittedUseCheck = false;
485 // Multiple uses of actual result?
486 emitCheck(RootName + ".hasOneUse()");
487 EmittedUseCheck = true;
489 // If the immediate use can somehow reach this node through another
490 // path, then can't fold it either or it will create a cycle.
491 // e.g. In the following diagram, XX can reach ld through YY. If
492 // ld is folded into XX, then YY is both a predecessor and a successor
502 bool NeedCheck = P != Pattern;
504 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
506 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
507 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
508 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
509 PInfo.getNumOperands() > 1 ||
510 PInfo.hasProperty(SDNPHasChain) ||
511 PInfo.hasProperty(SDNPInFlag) ||
512 PInfo.hasProperty(SDNPOptInFlag);
516 std::string ParentName(RootName.begin(), RootName.end()-1);
517 emitCheck("CanBeFoldedBy(" + RootName + ".getNode(), " + ParentName +
518 ".getNode(), N.getNode())");
525 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
526 "IsChainCompatible(" + ChainName + ".getNode(), " +
527 RootName + ".getNode()))");
528 OrigChains.push_back(std::make_pair(ChainName, RootName));
531 ChainName = "Chain" + ChainSuffix;
532 emitInit("SDValue " + ChainName + " = " + RootName +
537 // Don't fold any node which reads or writes a flag and has multiple uses.
538 // FIXME: We really need to separate the concepts of flag and "glue". Those
539 // real flag results, e.g. X86CMP output, can have multiple uses.
540 // FIXME: If the optional incoming flag does not exist. Then it is ok to
543 (PatternHasProperty(N, SDNPInFlag, CGP) ||
544 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
545 PatternHasProperty(N, SDNPOutFlag, CGP))) {
546 if (!EmittedUseCheck) {
547 // Multiple uses of actual result?
548 emitCheck(RootName + ".hasOneUse()");
552 // If there are node predicates for this, emit the calls.
553 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
554 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
556 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
557 // a constant without a predicate fn that has more that one bit set, handle
558 // this as a special case. This is usually for targets that have special
559 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
560 // handling stuff). Using these instructions is often far more efficient
561 // than materializing the constant. Unfortunately, both the instcombiner
562 // and the dag combiner can often infer that bits are dead, and thus drop
563 // them from the mask in the dag. For example, it might turn 'AND X, 255'
564 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
567 (N->getOperator()->getName() == "and" ||
568 N->getOperator()->getName() == "or") &&
569 N->getChild(1)->isLeaf() &&
570 N->getChild(1)->getPredicateFns().empty()) {
571 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
572 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
573 emitInit("SDValue " + RootName + "0" + " = " +
574 RootName + ".getOperand(" + utostr(0) + ");");
575 emitInit("SDValue " + RootName + "1" + " = " +
576 RootName + ".getOperand(" + utostr(1) + ");");
578 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
579 const char *MaskPredicate = N->getOperator()->getName() == "or"
580 ? "CheckOrMask(" : "CheckAndMask(";
581 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
582 RootName + "1), INT64_C(" + itostr(II->getValue()) + "))");
584 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
585 ChainSuffix + utostr(0), FoundChain);
591 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
592 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
593 RootName + ".getOperand(" +utostr(OpNo) + ");");
595 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
596 ChainSuffix + utostr(OpNo), FoundChain);
599 // Handle cases when root is a complex pattern.
600 const ComplexPattern *CP;
601 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
602 std::string Fn = CP->getSelectFunc();
603 unsigned NumOps = CP->getNumOperands();
604 for (unsigned i = 0; i < NumOps; ++i) {
605 emitDecl("CPTmp" + utostr(i));
606 emitCode("SDValue CPTmp" + utostr(i) + ";");
608 if (CP->hasProperty(SDNPHasChain)) {
609 emitDecl("CPInChain");
610 emitDecl("Chain" + ChainSuffix);
611 emitCode("SDValue CPInChain;");
612 emitCode("SDValue Chain" + ChainSuffix + ";");
615 std::string Code = Fn + "(" + RootName + ", " + RootName;
616 for (unsigned i = 0; i < NumOps; i++)
617 Code += ", CPTmp" + utostr(i);
618 if (CP->hasProperty(SDNPHasChain)) {
619 ChainName = "Chain" + ChainSuffix;
620 Code += ", CPInChain, Chain" + ChainSuffix;
622 emitCheck(Code + ")");
626 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
627 const std::string &RootName,
628 const std::string &ParentRootName,
629 const std::string &ChainSuffix, bool &FoundChain) {
630 if (!Child->isLeaf()) {
631 // If it's not a leaf, recursively match.
632 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
633 emitCheck(RootName + ".getOpcode() == " +
634 CInfo.getEnumName());
635 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
636 bool HasChain = false;
637 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
639 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
641 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
642 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
643 "Pattern folded multiple nodes which produce flags?");
644 FoldedFlag = std::make_pair(RootName,
645 CInfo.getNumResults() + (unsigned)HasChain);
648 // If this child has a name associated with it, capture it in VarMap. If
649 // we already saw this in the pattern, emit code to verify dagness.
650 if (!Child->getName().empty()) {
651 std::string &VarMapEntry = VariableMap[Child->getName()];
652 if (VarMapEntry.empty()) {
653 VarMapEntry = RootName;
655 // If we get here, this is a second reference to a specific name.
656 // Since we already have checked that the first reference is valid,
657 // we don't have to recursively match it, just check that it's the
658 // same as the previously named thing.
659 emitCheck(VarMapEntry + " == " + RootName);
660 Duplicates.insert(RootName);
665 // Handle leaves of various types.
666 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
667 Record *LeafRec = DI->getDef();
668 if (LeafRec->isSubClassOf("RegisterClass") ||
669 LeafRec->getName() == "ptr_rc") {
670 // Handle register references. Nothing to do here.
671 } else if (LeafRec->isSubClassOf("Register")) {
672 // Handle register references.
673 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
674 // Handle complex pattern.
675 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
676 std::string Fn = CP->getSelectFunc();
677 unsigned NumOps = CP->getNumOperands();
678 for (unsigned i = 0; i < NumOps; ++i) {
679 emitDecl("CPTmp" + utostr(i));
680 emitCode("SDValue CPTmp" + utostr(i) + ";");
682 if (CP->hasProperty(SDNPHasChain)) {
683 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
684 FoldedChains.push_back(std::make_pair("CPInChain",
685 PInfo.getNumResults()));
686 ChainName = "Chain" + ChainSuffix;
687 emitDecl("CPInChain");
689 emitCode("SDValue CPInChain;");
690 emitCode("SDValue " + ChainName + ";");
693 std::string Code = Fn + "(";
694 if (CP->hasAttribute(CPAttrParentAsRoot)) {
695 Code += ParentRootName + ", ";
699 if (CP->hasProperty(SDNPHasChain)) {
700 std::string ParentName(RootName.begin(), RootName.end()-1);
701 Code += ParentName + ", ";
704 for (unsigned i = 0; i < NumOps; i++)
705 Code += ", CPTmp" + utostr(i);
706 if (CP->hasProperty(SDNPHasChain))
707 Code += ", CPInChain, Chain" + ChainSuffix;
708 emitCheck(Code + ")");
709 } else if (LeafRec->getName() == "srcvalue") {
710 // Place holder for SRCVALUE nodes. Nothing to do here.
711 } else if (LeafRec->isSubClassOf("ValueType")) {
712 // Make sure this is the specified value type.
713 emitCheck("cast<VTSDNode>(" + RootName +
714 ")->getVT() == MVT::" + LeafRec->getName());
715 } else if (LeafRec->isSubClassOf("CondCode")) {
716 // Make sure this is the specified cond code.
717 emitCheck("cast<CondCodeSDNode>(" + RootName +
718 ")->get() == ISD::" + LeafRec->getName());
724 assert(0 && "Unknown leaf type!");
727 // If there are node predicates for this, emit the calls.
728 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
729 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
731 } else if (IntInit *II =
732 dynamic_cast<IntInit*>(Child->getLeafValue())) {
733 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
734 unsigned CTmp = TmpNo++;
735 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
736 RootName + ")->getSExtValue();");
738 emitCheck("CN" + utostr(CTmp) + " == "
739 "INT64_C(" +itostr(II->getValue()) + ")");
744 assert(0 && "Unknown leaf type!");
749 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
750 /// we actually have to build a DAG!
751 std::vector<std::string>
752 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
753 bool InFlagDecled, bool ResNodeDecled,
754 bool LikeLeaf = false, bool isRoot = false) {
755 // List of arguments of getTargetNode() or SelectNodeTo().
756 std::vector<std::string> NodeOps;
757 // This is something selected from the pattern we matched.
758 if (!N->getName().empty()) {
759 const std::string &VarName = N->getName();
760 std::string Val = VariableMap[VarName];
761 bool ModifiedVal = false;
763 cerr << "Variable '" << VarName << " referenced but not defined "
764 << "and not caught earlier!\n";
767 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
768 // Already selected this operand, just return the tmpval.
769 NodeOps.push_back(Val);
773 const ComplexPattern *CP;
774 unsigned ResNo = TmpNo++;
775 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
776 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
777 std::string CastType;
778 std::string TmpVar = "Tmp" + utostr(ResNo);
779 switch (N->getTypeNum(0)) {
781 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
782 << " type as an immediate constant. Aborting\n";
784 case MVT::i1: CastType = "bool"; break;
785 case MVT::i8: CastType = "unsigned char"; break;
786 case MVT::i16: CastType = "unsigned short"; break;
787 case MVT::i32: CastType = "unsigned"; break;
788 case MVT::i64: CastType = "uint64_t"; break;
790 emitCode("SDValue " + TmpVar +
791 " = CurDAG->getTargetConstant(((" + CastType +
792 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
793 getEnumName(N->getTypeNum(0)) + ");");
794 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
795 // value if used multiple times by this pattern result.
798 NodeOps.push_back(Val);
799 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
800 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
801 std::string TmpVar = "Tmp" + utostr(ResNo);
802 emitCode("SDValue " + TmpVar +
803 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
804 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
805 Val + ")->getValueType(0));");
806 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
807 // value if used multiple times by this pattern result.
810 NodeOps.push_back(Val);
811 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
812 Record *Op = OperatorMap[N->getName()];
813 // Transform ExternalSymbol to TargetExternalSymbol
814 if (Op && Op->getName() == "externalsym") {
815 std::string TmpVar = "Tmp"+utostr(ResNo);
816 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
817 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
818 Val + ")->getSymbol(), " +
819 getEnumName(N->getTypeNum(0)) + ");");
820 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
821 // this value if used multiple times by this pattern result.
825 NodeOps.push_back(Val);
826 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
827 || N->getOperator()->getName() == "tglobaltlsaddr")) {
828 Record *Op = OperatorMap[N->getName()];
829 // Transform GlobalAddress to TargetGlobalAddress
830 if (Op && (Op->getName() == "globaladdr" ||
831 Op->getName() == "globaltlsaddr")) {
832 std::string TmpVar = "Tmp" + utostr(ResNo);
833 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
834 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
835 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
837 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
838 // this value if used multiple times by this pattern result.
842 NodeOps.push_back(Val);
843 } else if (!N->isLeaf()
844 && (N->getOperator()->getName() == "texternalsym"
845 || N->getOperator()->getName() == "tconstpool")) {
846 // Do not rewrite the variable name, since we don't generate a new
848 NodeOps.push_back(Val);
849 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
850 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
851 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
852 NodeOps.push_back("CPTmp" + utostr(i));
855 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
856 // node even if it isn't one. Don't select it.
858 emitCode("AddToISelQueue(" + Val + ");");
859 if (isRoot && N->isLeaf()) {
860 emitCode("ReplaceUses(N, " + Val + ");");
861 emitCode("return NULL;");
864 NodeOps.push_back(Val);
868 VariableMap[VarName] = Val;
873 // If this is an explicit register reference, handle it.
874 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
875 unsigned ResNo = TmpNo++;
876 if (DI->getDef()->isSubClassOf("Register")) {
877 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
878 getQualifiedName(DI->getDef()) + ", " +
879 getEnumName(N->getTypeNum(0)) + ");");
880 NodeOps.push_back("Tmp" + utostr(ResNo));
882 } else if (DI->getDef()->getName() == "zero_reg") {
883 emitCode("SDValue Tmp" + utostr(ResNo) +
884 " = CurDAG->getRegister(0, " +
885 getEnumName(N->getTypeNum(0)) + ");");
886 NodeOps.push_back("Tmp" + utostr(ResNo));
889 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
890 unsigned ResNo = TmpNo++;
891 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
892 emitCode("SDValue Tmp" + utostr(ResNo) +
893 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
894 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
895 NodeOps.push_back("Tmp" + utostr(ResNo));
902 assert(0 && "Unknown leaf type!");
906 Record *Op = N->getOperator();
907 if (Op->isSubClassOf("Instruction")) {
908 const CodeGenTarget &CGT = CGP.getTargetInfo();
909 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
910 const DAGInstruction &Inst = CGP.getInstruction(Op);
911 const TreePattern *InstPat = Inst.getPattern();
912 // FIXME: Assume actual pattern comes before "implicit".
913 TreePatternNode *InstPatNode =
914 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
915 : (InstPat ? InstPat->getTree(0) : NULL);
916 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
917 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
919 bool IsVariadic = isRoot && II.isVariadic;
920 // FIXME: fix how we deal with physical register operands.
921 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
922 bool HasImpResults = isRoot && DstRegs.size() > 0;
923 bool NodeHasOptInFlag = isRoot &&
924 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
925 bool NodeHasInFlag = isRoot &&
926 PatternHasProperty(Pattern, SDNPInFlag, CGP);
927 bool NodeHasOutFlag = isRoot &&
928 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
929 bool NodeHasChain = InstPatNode &&
930 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
931 bool InputHasChain = isRoot &&
932 NodeHasProperty(Pattern, SDNPHasChain, CGP);
933 unsigned NumResults = Inst.getNumResults();
934 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
936 // Record output varargs info.
937 OutputIsVariadic = IsVariadic;
939 if (NodeHasOptInFlag) {
940 emitCode("bool HasInFlag = "
941 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
944 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
946 // How many results is this pattern expected to produce?
947 unsigned NumPatResults = 0;
948 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
949 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
950 if (VT != MVT::isVoid && VT != MVT::Flag)
954 if (OrigChains.size() > 0) {
955 // The original input chain is being ignored. If it is not just
956 // pointing to the op that's being folded, we should create a
957 // TokenFactor with it and the chain of the folded op as the new chain.
958 // We could potentially be doing multiple levels of folding, in that
959 // case, the TokenFactor can have more operands.
960 emitCode("SmallVector<SDValue, 8> InChains;");
961 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
962 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
963 OrigChains[i].second + ".getNode()) {");
964 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
965 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
968 emitCode("AddToISelQueue(" + ChainName + ");");
969 emitCode("InChains.push_back(" + ChainName + ");");
970 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
971 "&InChains[0], InChains.size());");
974 // Loop over all of the operands of the instruction pattern, emitting code
975 // to fill them all in. The node 'N' usually has number children equal to
976 // the number of input operands of the instruction. However, in cases
977 // where there are predicate operands for an instruction, we need to fill
978 // in the 'execute always' values. Match up the node operands to the
979 // instruction operands to do this.
980 std::vector<std::string> AllOps;
981 for (unsigned ChildNo = 0, InstOpNo = NumResults;
982 InstOpNo != II.OperandList.size(); ++InstOpNo) {
983 std::vector<std::string> Ops;
985 // Determine what to emit for this operand.
986 Record *OperandNode = II.OperandList[InstOpNo].Rec;
987 if ((OperandNode->isSubClassOf("PredicateOperand") ||
988 OperandNode->isSubClassOf("OptionalDefOperand")) &&
989 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
990 // This is a predicate or optional def operand; emit the
991 // 'default ops' operands.
992 const DAGDefaultOperand &DefaultOp =
993 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
994 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
995 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
996 InFlagDecled, ResNodeDecled);
997 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1000 // Otherwise this is a normal operand or a predicate operand without
1001 // 'execute always'; emit it.
1002 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1003 InFlagDecled, ResNodeDecled);
1004 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1009 // Emit all the chain and CopyToReg stuff.
1010 bool ChainEmitted = NodeHasChain;
1012 emitCode("AddToISelQueue(" + ChainName + ");");
1013 if (NodeHasInFlag || HasImpInputs)
1014 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1015 InFlagDecled, ResNodeDecled, true);
1016 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1017 if (!InFlagDecled) {
1018 emitCode("SDValue InFlag(0, 0);");
1019 InFlagDecled = true;
1021 if (NodeHasOptInFlag) {
1022 emitCode("if (HasInFlag) {");
1023 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1024 emitCode(" AddToISelQueue(InFlag);");
1029 unsigned ResNo = TmpNo++;
1031 unsigned OpsNo = OpcNo;
1032 std::string CodePrefix;
1033 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1034 std::deque<std::string> After;
1035 std::string NodeName;
1037 NodeName = "Tmp" + utostr(ResNo);
1038 CodePrefix = "SDValue " + NodeName + "(";
1040 NodeName = "ResNode";
1041 if (!ResNodeDecled) {
1042 CodePrefix = "SDNode *" + NodeName + " = ";
1043 ResNodeDecled = true;
1045 CodePrefix = NodeName + " = ";
1048 std::string Code = "Opc" + utostr(OpcNo);
1050 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1052 // Output order: results, chain, flags
1054 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1055 Code += ", VT" + utostr(VTNo);
1056 emitVT(getEnumName(N->getTypeNum(0)));
1058 // Add types for implicit results in physical registers, scheduler will
1059 // care of adding copyfromreg nodes.
1060 for (unsigned i = 0; i < NumDstRegs; i++) {
1061 Record *RR = DstRegs[i];
1062 if (RR->isSubClassOf("Register")) {
1063 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1064 Code += ", " + getEnumName(RVT);
1068 Code += ", MVT::Other";
1070 Code += ", MVT::Flag";
1074 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1075 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1078 // Figure out whether any operands at the end of the op list are not
1079 // part of the variable section.
1080 std::string EndAdjust;
1081 if (NodeHasInFlag || HasImpInputs)
1082 EndAdjust = "-1"; // Always has one flag.
1083 else if (NodeHasOptInFlag)
1084 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1086 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1087 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1089 emitCode(" AddToISelQueue(N.getOperand(i));");
1090 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1094 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1096 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1097 std::vector<std::string>::const_iterator mi, mie;
1098 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1099 emitCode("SDValue LSI_" + *mi + " = "
1100 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1101 *mi + ")->getMemOperand());");
1103 emitCode("Ops" + utostr(OpsNo) + ".push_back(LSI_" + *mi + ");");
1105 AllOps.push_back("LSI_" + *mi);
1111 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1113 AllOps.push_back(ChainName);
1117 if (NodeHasInFlag || HasImpInputs)
1118 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1119 else if (NodeHasOptInFlag) {
1120 emitCode("if (HasInFlag)");
1121 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1123 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1125 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1126 AllOps.push_back("InFlag");
1128 unsigned NumOps = AllOps.size();
1130 if (!NodeHasOptInFlag && NumOps < 4) {
1131 for (unsigned i = 0; i != NumOps; ++i)
1132 Code += ", " + AllOps[i];
1134 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1135 for (unsigned i = 0; i != NumOps; ++i) {
1136 OpsCode += AllOps[i];
1140 emitCode(OpsCode + " };");
1141 Code += ", Ops" + utostr(OpsNo) + ", ";
1142 if (NodeHasOptInFlag) {
1143 Code += "HasInFlag ? ";
1144 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1146 Code += utostr(NumOps);
1153 std::vector<std::string> ReplaceFroms;
1154 std::vector<std::string> ReplaceTos;
1156 NodeOps.push_back("Tmp" + utostr(ResNo));
1159 if (NodeHasOutFlag) {
1160 if (!InFlagDecled) {
1161 After.push_back("SDValue InFlag(ResNode, " +
1162 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1164 InFlagDecled = true;
1166 After.push_back("InFlag = SDValue(ResNode, " +
1167 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1171 if (FoldedChains.size() > 0) {
1173 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1174 ReplaceFroms.push_back("SDValue(" +
1175 FoldedChains[j].first + ".getNode(), " +
1176 utostr(FoldedChains[j].second) +
1178 ReplaceTos.push_back("SDValue(ResNode, " +
1179 utostr(NumResults+NumDstRegs) + ")");
1183 if (NodeHasOutFlag) {
1184 if (FoldedFlag.first != "") {
1185 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1186 utostr(FoldedFlag.second) + ")");
1187 ReplaceTos.push_back("InFlag");
1189 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1190 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1191 utostr(NumPatResults + (unsigned)InputHasChain)
1193 ReplaceTos.push_back("InFlag");
1197 if (!ReplaceFroms.empty() && InputHasChain) {
1198 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1199 utostr(NumPatResults) + ")");
1200 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1201 ChainName + ".getResNo()" + ")");
1202 ChainAssignmentNeeded |= NodeHasChain;
1205 // User does not expect the instruction would produce a chain!
1206 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1208 } else if (InputHasChain && !NodeHasChain) {
1209 // One of the inner node produces a chain.
1210 if (NodeHasOutFlag) {
1211 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1212 utostr(NumPatResults+1) +
1214 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1216 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1217 utostr(NumPatResults) + ")");
1218 ReplaceTos.push_back(ChainName);
1222 if (ChainAssignmentNeeded) {
1223 // Remember which op produces the chain.
1224 std::string ChainAssign;
1226 ChainAssign = ChainName + " = SDValue(" + NodeName +
1227 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1229 ChainAssign = ChainName + " = SDValue(" + NodeName +
1230 ", " + utostr(NumResults+NumDstRegs) + ");";
1232 After.push_front(ChainAssign);
1235 if (ReplaceFroms.size() == 1) {
1236 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1237 ReplaceTos[0] + ");");
1238 } else if (!ReplaceFroms.empty()) {
1239 After.push_back("const SDValue Froms[] = {");
1240 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1241 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1242 After.push_back("};");
1243 After.push_back("const SDValue Tos[] = {");
1244 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1245 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1246 After.push_back("};");
1247 After.push_back("ReplaceUses(Froms, Tos, " +
1248 itostr(ReplaceFroms.size()) + ");");
1251 // We prefer to use SelectNodeTo since it avoids allocation when
1252 // possible and it avoids CSE map recalculation for the node's
1253 // users, however it's tricky to use in a non-root context.
1255 // We also don't use if the pattern replacement is being used to
1256 // jettison a chain result, since morphing the node in place
1257 // would leave users of the chain dangling.
1259 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1260 Code = "CurDAG->getTargetNode(" + Code;
1262 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1266 CodePrefix = "return ";
1268 After.push_back("return ResNode;");
1271 emitCode(CodePrefix + Code + ");");
1272 for (unsigned i = 0, e = After.size(); i != e; ++i)
1277 if (Op->isSubClassOf("SDNodeXForm")) {
1278 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1279 // PatLeaf node - the operand may or may not be a leaf node. But it should
1281 std::vector<std::string> Ops =
1282 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1283 ResNodeDecled, true);
1284 unsigned ResNo = TmpNo++;
1285 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1286 + "(" + Ops.back() + ".getNode());");
1287 NodeOps.push_back("Tmp" + utostr(ResNo));
1289 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1295 throw std::string("Unknown node in result pattern!");
1298 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1299 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1300 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1301 /// for, this returns true otherwise false if Pat has all types.
1302 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1303 const std::string &Prefix, bool isRoot = false) {
1305 if (Pat->getExtTypes() != Other->getExtTypes()) {
1306 // Move a type over from 'other' to 'pat'.
1307 Pat->setTypes(Other->getExtTypes());
1308 // The top level node type is checked outside of the select function.
1310 emitCheck(Prefix + ".getNode()->getValueType(0) == " +
1311 getName(Pat->getTypeNum(0)));
1316 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1317 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1318 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1319 Prefix + utostr(OpNo)))
1325 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1327 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1328 bool &ChainEmitted, bool &InFlagDecled,
1329 bool &ResNodeDecled, bool isRoot = false) {
1330 const CodeGenTarget &T = CGP.getTargetInfo();
1332 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1333 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1334 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1335 TreePatternNode *Child = N->getChild(i);
1336 if (!Child->isLeaf()) {
1337 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1338 InFlagDecled, ResNodeDecled);
1340 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1341 if (!Child->getName().empty()) {
1342 std::string Name = RootName + utostr(OpNo);
1343 if (Duplicates.find(Name) != Duplicates.end())
1344 // A duplicate! Do not emit a copy for this node.
1348 Record *RR = DI->getDef();
1349 if (RR->isSubClassOf("Register")) {
1350 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1351 if (RVT == MVT::Flag) {
1352 if (!InFlagDecled) {
1353 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1354 InFlagDecled = true;
1356 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1357 emitCode("AddToISelQueue(InFlag);");
1359 if (!ChainEmitted) {
1360 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1361 ChainName = "Chain";
1362 ChainEmitted = true;
1364 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1365 if (!InFlagDecled) {
1366 emitCode("SDValue InFlag(0, 0);");
1367 InFlagDecled = true;
1369 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1370 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1371 ", " + getQualifiedName(RR) +
1372 ", " + RootName + utostr(OpNo) + ", InFlag).getNode();");
1373 ResNodeDecled = true;
1374 emitCode(ChainName + " = SDValue(ResNode, 0);");
1375 emitCode("InFlag = SDValue(ResNode, 1);");
1383 if (!InFlagDecled) {
1384 emitCode("SDValue InFlag = " + RootName +
1385 ".getOperand(" + utostr(OpNo) + ");");
1386 InFlagDecled = true;
1388 emitCode("InFlag = " + RootName +
1389 ".getOperand(" + utostr(OpNo) + ");");
1390 emitCode("AddToISelQueue(InFlag);");
1395 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1396 /// stream to match the pattern, and generate the code for the match if it
1397 /// succeeds. Returns true if the pattern is not guaranteed to match.
1398 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1399 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1400 std::set<std::string> &GeneratedDecl,
1401 std::vector<std::string> &TargetOpcodes,
1402 std::vector<std::string> &TargetVTs,
1403 bool &OutputIsVariadic,
1404 unsigned &NumInputRootOps) {
1405 OutputIsVariadic = false;
1406 NumInputRootOps = 0;
1408 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1409 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1410 GeneratedCode, GeneratedDecl,
1411 TargetOpcodes, TargetVTs,
1412 OutputIsVariadic, NumInputRootOps);
1414 // Emit the matcher, capturing named arguments in VariableMap.
1415 bool FoundChain = false;
1416 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1418 // TP - Get *SOME* tree pattern, we don't care which.
1419 TreePattern &TP = *CGP.pf_begin()->second;
1421 // At this point, we know that we structurally match the pattern, but the
1422 // types of the nodes may not match. Figure out the fewest number of type
1423 // comparisons we need to emit. For example, if there is only one integer
1424 // type supported by a target, there should be no type comparisons at all for
1425 // integer patterns!
1427 // To figure out the fewest number of type checks needed, clone the pattern,
1428 // remove the types, then perform type inference on the pattern as a whole.
1429 // If there are unresolved types, emit an explicit check for those types,
1430 // apply the type to the tree, then rerun type inference. Iterate until all
1431 // types are resolved.
1433 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1434 RemoveAllTypes(Pat);
1437 // Resolve/propagate as many types as possible.
1439 bool MadeChange = true;
1441 MadeChange = Pat->ApplyTypeConstraints(TP,
1442 true/*Ignore reg constraints*/);
1444 assert(0 && "Error: could not find consistent types for something we"
1445 " already decided was ok!");
1449 // Insert a check for an unresolved type and add it to the tree. If we find
1450 // an unresolved type to add a check for, this returns true and we iterate,
1451 // otherwise we are done.
1452 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1454 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1455 false, false, false, true);
1459 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1460 /// a line causes any of them to be empty, remove them and return true when
1462 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1463 std::vector<std::pair<unsigned, std::string> > > >
1465 bool ErasedPatterns = false;
1466 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1467 Patterns[i].second.pop_back();
1468 if (Patterns[i].second.empty()) {
1469 Patterns.erase(Patterns.begin()+i);
1471 ErasedPatterns = true;
1474 return ErasedPatterns;
1477 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1478 /// code together between the patterns.
1479 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1480 std::vector<std::pair<unsigned, std::string> > > >
1481 &Patterns, unsigned Indent,
1483 typedef std::pair<unsigned, std::string> CodeLine;
1484 typedef std::vector<CodeLine> CodeList;
1485 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1487 if (Patterns.empty()) return;
1489 // Figure out how many patterns share the next code line. Explicitly copy
1490 // FirstCodeLine so that we don't invalidate a reference when changing
1492 const CodeLine FirstCodeLine = Patterns.back().second.back();
1493 unsigned LastMatch = Patterns.size()-1;
1494 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1497 // If not all patterns share this line, split the list into two pieces. The
1498 // first chunk will use this line, the second chunk won't.
1499 if (LastMatch != 0) {
1500 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1501 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1503 // FIXME: Emit braces?
1504 if (Shared.size() == 1) {
1505 const PatternToMatch &Pattern = *Shared.back().first;
1506 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1507 Pattern.getSrcPattern()->print(OS);
1508 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1509 Pattern.getDstPattern()->print(OS);
1511 unsigned AddedComplexity = Pattern.getAddedComplexity();
1512 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1513 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1515 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1517 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1519 if (FirstCodeLine.first != 1) {
1520 OS << std::string(Indent, ' ') << "{\n";
1523 EmitPatterns(Shared, Indent, OS);
1524 if (FirstCodeLine.first != 1) {
1526 OS << std::string(Indent, ' ') << "}\n";
1529 if (Other.size() == 1) {
1530 const PatternToMatch &Pattern = *Other.back().first;
1531 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1532 Pattern.getSrcPattern()->print(OS);
1533 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1534 Pattern.getDstPattern()->print(OS);
1536 unsigned AddedComplexity = Pattern.getAddedComplexity();
1537 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1538 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1540 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1542 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1544 EmitPatterns(Other, Indent, OS);
1548 // Remove this code from all of the patterns that share it.
1549 bool ErasedPatterns = EraseCodeLine(Patterns);
1551 bool isPredicate = FirstCodeLine.first == 1;
1553 // Otherwise, every pattern in the list has this line. Emit it.
1556 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1558 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1560 // If the next code line is another predicate, and if all of the pattern
1561 // in this group share the same next line, emit it inline now. Do this
1562 // until we run out of common predicates.
1563 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1564 // Check that all of fhe patterns in Patterns end with the same predicate.
1565 bool AllEndWithSamePredicate = true;
1566 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1567 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1568 AllEndWithSamePredicate = false;
1571 // If all of the predicates aren't the same, we can't share them.
1572 if (!AllEndWithSamePredicate) break;
1574 // Otherwise we can. Emit it shared now.
1575 OS << " &&\n" << std::string(Indent+4, ' ')
1576 << Patterns.back().second.back().second;
1577 ErasedPatterns = EraseCodeLine(Patterns);
1584 EmitPatterns(Patterns, Indent, OS);
1587 OS << std::string(Indent-2, ' ') << "}\n";
1590 static std::string getLegalCName(std::string OpName) {
1591 std::string::size_type pos = OpName.find("::");
1592 if (pos != std::string::npos)
1593 OpName.replace(pos, 2, "_");
1597 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1598 const CodeGenTarget &Target = CGP.getTargetInfo();
1600 // Get the namespace to insert instructions into.
1601 std::string InstNS = Target.getInstNamespace();
1602 if (!InstNS.empty()) InstNS += "::";
1604 // Group the patterns by their top-level opcodes.
1605 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1606 // All unique target node emission functions.
1607 std::map<std::string, unsigned> EmitFunctions;
1608 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1609 E = CGP.ptm_end(); I != E; ++I) {
1610 const PatternToMatch &Pattern = *I;
1612 TreePatternNode *Node = Pattern.getSrcPattern();
1613 if (!Node->isLeaf()) {
1614 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1615 push_back(&Pattern);
1617 const ComplexPattern *CP;
1618 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1619 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1620 push_back(&Pattern);
1621 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1622 std::vector<Record*> OpNodes = CP->getRootNodes();
1623 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1624 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1625 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1629 cerr << "Unrecognized opcode '";
1631 cerr << "' on tree pattern '";
1632 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1638 // For each opcode, there might be multiple select functions, one per
1639 // ValueType of the node (or its first operand if it doesn't produce a
1640 // non-chain result.
1641 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1643 // Emit one Select_* method for each top-level opcode. We do this instead of
1644 // emitting one giant switch statement to support compilers where this will
1645 // result in the recursive functions taking less stack space.
1646 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1647 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1648 PBOI != E; ++PBOI) {
1649 const std::string &OpName = PBOI->first;
1650 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1651 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1653 // Split them into groups by type.
1654 std::map<MVT::SimpleValueType,
1655 std::vector<const PatternToMatch*> > PatternsByType;
1656 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1657 const PatternToMatch *Pat = PatternsOfOp[i];
1658 TreePatternNode *SrcPat = Pat->getSrcPattern();
1659 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1662 for (std::map<MVT::SimpleValueType,
1663 std::vector<const PatternToMatch*> >::iterator
1664 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1666 MVT::SimpleValueType OpVT = II->first;
1667 std::vector<const PatternToMatch*> &Patterns = II->second;
1668 typedef std::pair<unsigned, std::string> CodeLine;
1669 typedef std::vector<CodeLine> CodeList;
1670 typedef CodeList::iterator CodeListI;
1672 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1673 std::vector<std::vector<std::string> > PatternOpcodes;
1674 std::vector<std::vector<std::string> > PatternVTs;
1675 std::vector<std::set<std::string> > PatternDecls;
1676 std::vector<bool> OutputIsVariadicFlags;
1677 std::vector<unsigned> NumInputRootOpsCounts;
1678 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1679 CodeList GeneratedCode;
1680 std::set<std::string> GeneratedDecl;
1681 std::vector<std::string> TargetOpcodes;
1682 std::vector<std::string> TargetVTs;
1683 bool OutputIsVariadic;
1684 unsigned NumInputRootOps;
1685 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1686 TargetOpcodes, TargetVTs,
1687 OutputIsVariadic, NumInputRootOps);
1688 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1689 PatternDecls.push_back(GeneratedDecl);
1690 PatternOpcodes.push_back(TargetOpcodes);
1691 PatternVTs.push_back(TargetVTs);
1692 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1693 NumInputRootOpsCounts.push_back(NumInputRootOps);
1696 // Factor target node emission code (emitted by EmitResultCode) into
1697 // separate functions. Uniquing and share them among all instruction
1698 // selection routines.
1699 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1700 CodeList &GeneratedCode = CodeForPatterns[i].second;
1701 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1702 std::vector<std::string> &TargetVTs = PatternVTs[i];
1703 std::set<std::string> Decls = PatternDecls[i];
1704 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1705 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1706 std::vector<std::string> AddedInits;
1707 int CodeSize = (int)GeneratedCode.size();
1709 for (int j = CodeSize-1; j >= 0; --j) {
1710 if (LastPred == -1 && GeneratedCode[j].first == 1)
1712 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1713 AddedInits.push_back(GeneratedCode[j].second);
1716 std::string CalleeCode = "(const SDValue &N";
1717 std::string CallerCode = "(N";
1718 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1719 CalleeCode += ", unsigned Opc" + utostr(j);
1720 CallerCode += ", " + TargetOpcodes[j];
1722 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1723 CalleeCode += ", MVT VT" + utostr(j);
1724 CallerCode += ", " + TargetVTs[j];
1726 for (std::set<std::string>::iterator
1727 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1728 std::string Name = *I;
1729 CalleeCode += ", SDValue &" + Name;
1730 CallerCode += ", " + Name;
1733 if (OutputIsVariadic) {
1734 CalleeCode += ", unsigned NumInputRootOps";
1735 CallerCode += ", " + utostr(NumInputRootOps);
1740 // Prevent emission routines from being inlined to reduce selection
1741 // routines stack frame sizes.
1742 CalleeCode += "DISABLE_INLINE ";
1743 CalleeCode += "{\n";
1745 for (std::vector<std::string>::const_reverse_iterator
1746 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1747 CalleeCode += " " + *I + "\n";
1749 for (int j = LastPred+1; j < CodeSize; ++j)
1750 CalleeCode += " " + GeneratedCode[j].second + "\n";
1751 for (int j = LastPred+1; j < CodeSize; ++j)
1752 GeneratedCode.pop_back();
1753 CalleeCode += "}\n";
1755 // Uniquing the emission routines.
1756 unsigned EmitFuncNum;
1757 std::map<std::string, unsigned>::iterator EFI =
1758 EmitFunctions.find(CalleeCode);
1759 if (EFI != EmitFunctions.end()) {
1760 EmitFuncNum = EFI->second;
1762 EmitFuncNum = EmitFunctions.size();
1763 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1764 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1767 // Replace the emission code within selection routines with calls to the
1768 // emission functions.
1769 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1770 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1774 std::string OpVTStr;
1775 if (OpVT == MVT::iPTR) {
1777 } else if (OpVT == MVT::iPTRAny) {
1778 OpVTStr = "_iPTRAny";
1779 } else if (OpVT == MVT::isVoid) {
1780 // Nodes with a void result actually have a first result type of either
1781 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1782 // void to this case, we handle it specially here.
1784 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1786 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1787 OpcodeVTMap.find(OpName);
1788 if (OpVTI == OpcodeVTMap.end()) {
1789 std::vector<std::string> VTSet;
1790 VTSet.push_back(OpVTStr);
1791 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1793 OpVTI->second.push_back(OpVTStr);
1795 OS << "SDNode *Select_" << getLegalCName(OpName)
1796 << OpVTStr << "(const SDValue &N) {\n";
1798 // We want to emit all of the matching code now. However, we want to emit
1799 // the matches in order of minimal cost. Sort the patterns so the least
1800 // cost one is at the start.
1801 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1802 PatternSortingPredicate(CGP));
1804 // Scan the code to see if all of the patterns are reachable and if it is
1805 // possible that the last one might not match.
1806 bool mightNotMatch = true;
1807 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1808 CodeList &GeneratedCode = CodeForPatterns[i].second;
1809 mightNotMatch = false;
1811 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1812 if (GeneratedCode[j].first == 1) { // predicate.
1813 mightNotMatch = true;
1818 // If this pattern definitely matches, and if it isn't the last one, the
1819 // patterns after it CANNOT ever match. Error out.
1820 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1821 cerr << "Pattern '";
1822 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1823 cerr << "' is impossible to select!\n";
1828 // Loop through and reverse all of the CodeList vectors, as we will be
1829 // accessing them from their logical front, but accessing the end of a
1830 // vector is more efficient.
1831 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1832 CodeList &GeneratedCode = CodeForPatterns[i].second;
1833 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1836 // Next, reverse the list of patterns itself for the same reason.
1837 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1839 // Emit all of the patterns now, grouped together to share code.
1840 EmitPatterns(CodeForPatterns, 2, OS);
1842 // If the last pattern has predicates (which could fail) emit code to
1843 // catch the case where nothing handles a pattern.
1844 if (mightNotMatch) {
1846 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1847 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1848 OpName != "ISD::INTRINSIC_VOID")
1849 OS << " CannotYetSelect(N);\n";
1851 OS << " CannotYetSelectIntrinsic(N);\n";
1853 OS << " return NULL;\n";
1859 // Emit boilerplate.
1860 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1861 << " std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());\n"
1862 << " SelectInlineAsmMemoryOperands(Ops);\n\n"
1864 << " // Ensure that the asm operands are themselves selected.\n"
1865 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1866 << " AddToISelQueue(Ops[j]);\n\n"
1868 << " std::vector<MVT> VTs;\n"
1869 << " VTs.push_back(MVT::Other);\n"
1870 << " VTs.push_back(MVT::Flag);\n"
1871 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1873 << " return New.getNode();\n"
1876 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1877 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,\n"
1878 << " N.getValueType());\n"
1881 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1882 << " SDValue Chain = N.getOperand(0);\n"
1883 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1884 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1885 << " AddToISelQueue(Chain);\n"
1886 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,\n"
1887 << " MVT::Other, Tmp, Chain);\n"
1890 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1891 << " SDValue Chain = N.getOperand(0);\n"
1892 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1893 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1894 << " AddToISelQueue(Chain);\n"
1895 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,\n"
1896 << " MVT::Other, Tmp, Chain);\n"
1899 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1900 << " SDValue Chain = N.getOperand(0);\n"
1901 << " SDValue N1 = N.getOperand(1);\n"
1902 << " SDValue N2 = N.getOperand(2);\n"
1903 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1904 << " CannotYetSelect(N);\n"
1906 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1907 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1908 << " SDValue Tmp1 = "
1909 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1910 << " SDValue Tmp2 = "
1911 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1912 << " AddToISelQueue(Chain);\n"
1913 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DECLARE,\n"
1914 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
1917 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1918 << " SDValue N0 = N.getOperand(0);\n"
1919 << " SDValue N1 = N.getOperand(1);\n"
1920 << " unsigned C = cast<ConstantSDNode>(N1)->getZExtValue();\n"
1921 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1922 << " AddToISelQueue(N0);\n"
1923 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EXTRACT_SUBREG,\n"
1924 << " N.getValueType(), N0, Tmp);\n"
1927 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1928 << " SDValue N0 = N.getOperand(0);\n"
1929 << " SDValue N1 = N.getOperand(1);\n"
1930 << " SDValue N2 = N.getOperand(2);\n"
1931 << " unsigned C = cast<ConstantSDNode>(N2)->getZExtValue();\n"
1932 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1933 << " AddToISelQueue(N1);\n"
1934 << " AddToISelQueue(N0);\n"
1935 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::INSERT_SUBREG,\n"
1936 << " N.getValueType(), N0, N1, Tmp);\n"
1939 OS << "// The main instruction selector code.\n"
1940 << "SDNode *SelectCode(SDValue N) {\n"
1941 << " if (N.isMachineOpcode()) {\n"
1942 << " return NULL; // Already selected.\n"
1944 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT();\n"
1945 << " switch (N.getOpcode()) {\n"
1946 << " default: break;\n"
1947 << " case ISD::EntryToken: // These leaves remain the same.\n"
1948 << " case ISD::BasicBlock:\n"
1949 << " case ISD::Register:\n"
1950 << " case ISD::HANDLENODE:\n"
1951 << " case ISD::TargetConstant:\n"
1952 << " case ISD::TargetConstantFP:\n"
1953 << " case ISD::TargetConstantPool:\n"
1954 << " case ISD::TargetFrameIndex:\n"
1955 << " case ISD::TargetExternalSymbol:\n"
1956 << " case ISD::TargetJumpTable:\n"
1957 << " case ISD::TargetGlobalTLSAddress:\n"
1958 << " case ISD::TargetGlobalAddress: {\n"
1959 << " return NULL;\n"
1961 << " case ISD::AssertSext:\n"
1962 << " case ISD::AssertZext: {\n"
1963 << " AddToISelQueue(N.getOperand(0));\n"
1964 << " ReplaceUses(N, N.getOperand(0));\n"
1965 << " return NULL;\n"
1967 << " case ISD::TokenFactor:\n"
1968 << " case ISD::CopyFromReg:\n"
1969 << " case ISD::CopyToReg: {\n"
1970 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1971 << " AddToISelQueue(N.getOperand(i));\n"
1972 << " return NULL;\n"
1974 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1975 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1976 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1977 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
1978 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1979 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1980 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1982 // Loop over all of the case statements, emiting a call to each method we
1984 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1985 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1986 PBOI != E; ++PBOI) {
1987 const std::string &OpName = PBOI->first;
1988 // Potentially multiple versions of select for this opcode. One for each
1989 // ValueType of the node (or its first true operand if it doesn't produce a
1991 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1992 OpcodeVTMap.find(OpName);
1993 std::vector<std::string> &OpVTs = OpVTI->second;
1994 OS << " case " << OpName << ": {\n";
1995 // Keep track of whether we see a pattern that has an iPtr result.
1996 bool HasPtrPattern = false;
1997 bool HasDefaultPattern = false;
1999 OS << " switch (NVT) {\n";
2000 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2001 std::string &VTStr = OpVTs[i];
2002 if (VTStr.empty()) {
2003 HasDefaultPattern = true;
2007 // If this is a match on iPTR: don't emit it directly, we need special
2009 if (VTStr == "_iPTR") {
2010 HasPtrPattern = true;
2013 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2014 << " return Select_" << getLegalCName(OpName)
2015 << VTStr << "(N);\n";
2017 OS << " default:\n";
2019 // If there is an iPTR result version of this pattern, emit it here.
2020 if (HasPtrPattern) {
2021 OS << " if (TLI.getPointerTy() == NVT)\n";
2022 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2024 if (HasDefaultPattern) {
2025 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2033 OS << " } // end of big switch.\n\n"
2034 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2035 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2036 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2037 << " CannotYetSelect(N);\n"
2039 << " CannotYetSelectIntrinsic(N);\n"
2041 << " return NULL;\n"
2044 OS << "void CannotYetSelect(SDValue N) DISABLE_INLINE {\n"
2045 << " cerr << \"Cannot yet select: \";\n"
2046 << " N.getNode()->dump(CurDAG);\n"
2047 << " cerr << '\\n';\n"
2051 OS << "void CannotYetSelectIntrinsic(SDValue N) DISABLE_INLINE {\n"
2052 << " cerr << \"Cannot yet select: \";\n"
2053 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2054 << "N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();\n"
2055 << " cerr << \"intrinsic %\"<< "
2056 << "Intrinsic::getName((Intrinsic::ID)iid);\n"
2057 << " cerr << '\\n';\n"
2062 void DAGISelEmitter::run(std::ostream &OS) {
2063 EmitSourceFileHeader("DAG Instruction Selector for the " +
2064 CGP.getTargetInfo().getName() + " target", OS);
2066 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2067 << "// *** instruction selector class. These functions are really "
2070 OS << "// Include standard, target-independent definitions and methods used\n"
2071 << "// by the instruction selector.\n";
2072 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
2074 EmitNodeTransforms(OS);
2075 EmitPredicateFunctions(OS);
2077 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2078 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2080 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2081 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2085 // At this point, we have full information about the 'Patterns' we need to
2086 // parse, both implicitly from instructions as well as from explicit pattern
2087 // definitions. Emit the resultant instruction selector.
2088 EmitInstructionSelector(OS);