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"
23 //===----------------------------------------------------------------------===//
24 // DAGISelEmitter Helper methods
27 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
29 static bool NodeIsComplexPattern(TreePatternNode *N) {
30 return (N->isLeaf() &&
31 dynamic_cast<DefInit*>(N->getLeafValue()) &&
32 static_cast<DefInit*>(N->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
36 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
38 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
39 CodeGenDAGPatterns &CGP) {
41 dynamic_cast<DefInit*>(N->getLeafValue()) &&
42 static_cast<DefInit*>(N->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
44 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
50 /// getPatternSize - Return the 'size' of this pattern. We want to match large
51 /// patterns before small ones. This is used to determine the size of a
53 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
54 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR) &&
59 "Not a valid pattern node to size!");
60 unsigned Size = 3; // The node itself.
61 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
71 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
73 Size += AM->getNumOperands() * 3;
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P->getPredicateFn().empty())
80 // Count children in the count if they are also nodes.
81 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82 TreePatternNode *Child = P->getChild(i);
83 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
84 Size += getPatternSize(Child, CGP);
85 else if (Child->isLeaf()) {
86 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
87 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
88 else if (NodeIsComplexPattern(Child))
89 Size += getPatternSize(Child, CGP);
90 else if (!Child->getPredicateFn().empty())
98 /// getResultPatternCost - Compute the number of instructions for this pattern.
99 /// This is a temporary hack. We should really include the instruction
100 /// latencies in this calculation.
101 static unsigned getResultPatternCost(TreePatternNode *P,
102 CodeGenDAGPatterns &CGP) {
103 if (P->isLeaf()) return 0;
106 Record *Op = P->getOperator();
107 if (Op->isSubClassOf("Instruction")) {
109 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
110 if (II.usesCustomDAGSchedInserter)
113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
114 Cost += getResultPatternCost(P->getChild(i), CGP);
118 /// getResultPatternCodeSize - Compute the code size of instructions for this
120 static unsigned getResultPatternSize(TreePatternNode *P,
121 CodeGenDAGPatterns &CGP) {
122 if (P->isLeaf()) return 0;
125 Record *Op = P->getOperator();
126 if (Op->isSubClassOf("Instruction")) {
127 Cost += Op->getValueAsInt("CodeSize");
129 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
130 Cost += getResultPatternSize(P->getChild(i), CGP);
134 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135 // In particular, we want to match maximal patterns first and lowest cost within
136 // a particular complexity first.
137 struct PatternSortingPredicate {
138 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139 CodeGenDAGPatterns &CGP;
141 bool operator()(const PatternToMatch *LHS,
142 const PatternToMatch *RHS) {
143 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
145 LHSSize += LHS->getAddedComplexity();
146 RHSSize += RHS->getAddedComplexity();
147 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
148 if (LHSSize < RHSSize) return false;
150 // If the patterns have equal complexity, compare generated instruction cost
151 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
153 if (LHSCost < RHSCost) return true;
154 if (LHSCost > RHSCost) return false;
156 return getResultPatternSize(LHS->getDstPattern(), CGP) <
157 getResultPatternSize(RHS->getDstPattern(), CGP);
161 /// getRegisterValueType - Look up and return the first ValueType of specified
162 /// RegisterClass record
163 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165 return RC->getValueTypeNum(0);
170 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171 /// type information from it.
172 static void RemoveAllTypes(TreePatternNode *N) {
175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176 RemoveAllTypes(N->getChild(i));
179 /// NodeHasProperty - return true if TreePatternNode has the specified
181 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
182 CodeGenDAGPatterns &CGP) {
184 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
186 return CP->hasProperty(Property);
189 Record *Operator = N->getOperator();
190 if (!Operator->isSubClassOf("SDNode")) return false;
192 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
195 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
196 CodeGenDAGPatterns &CGP) {
197 if (NodeHasProperty(N, Property, CGP))
200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201 TreePatternNode *Child = N->getChild(i);
202 if (PatternHasProperty(Child, Property, CGP))
209 //===----------------------------------------------------------------------===//
210 // Node Transformation emitter implementation.
212 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
215 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
216 NXsByNameTy NXsByName;
218 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
220 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
222 OS << "\n// Node transformations.\n";
224 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
226 Record *SDNode = I->second.first;
227 std::string Code = I->second.second;
229 if (Code.empty()) continue; // Empty code? Skip it.
231 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
232 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
234 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
236 if (ClassName != "SDNode")
237 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238 OS << Code << "\n}\n";
242 //===----------------------------------------------------------------------===//
243 // Predicate emitter implementation.
246 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247 OS << "\n// Predicate functions.\n";
249 // Walk the pattern fragments, adding them to a map, which sorts them by
251 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252 PFsByNameTy PFsByName;
254 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
256 PFsByName.insert(std::make_pair(I->first->getName(), *I));
259 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
261 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262 TreePattern *P = I->second.second;
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code = PatFragRecord->getValueAsCode("Predicate");
266 if (Code.empty()) continue;
268 if (P->getOnlyTree()->isLeaf())
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *N) {\n";
272 std::string ClassName =
273 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
274 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
276 OS << "inline bool Predicate_" << PatFragRecord->getName()
277 << "(SDNode *" << C2 << ") {\n";
278 if (ClassName != "SDNode")
279 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
281 OS << Code << "\n}\n";
288 //===----------------------------------------------------------------------===//
289 // PatternCodeEmitter implementation.
291 class PatternCodeEmitter {
293 CodeGenDAGPatterns &CGP;
296 ListInit *Predicates;
299 // Instruction selector pattern.
300 TreePatternNode *Pattern;
301 // Matched instruction.
302 TreePatternNode *Instruction;
304 // Node to name mapping
305 std::map<std::string, std::string> VariableMap;
306 // Node to operator mapping
307 std::map<std::string, Record*> OperatorMap;
308 // Names of all the folded nodes which produce chains.
309 std::vector<std::pair<std::string, unsigned> > FoldedChains;
310 // Original input chain(s).
311 std::vector<std::pair<std::string, std::string> > OrigChains;
312 std::set<std::string> Duplicates;
314 /// GeneratedCode - This is the buffer that we emit code to. The first int
315 /// indicates whether this is an exit predicate (something that should be
316 /// tested, and if true, the match fails) [when 1], or normal code to emit
317 /// [when 0], or initialization code to emit [when 2].
318 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
319 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
320 /// the set of patterns for each top-level opcode.
321 std::set<std::string> &GeneratedDecl;
322 /// TargetOpcodes - The target specific opcodes used by the resulting
324 std::vector<std::string> &TargetOpcodes;
325 std::vector<std::string> &TargetVTs;
327 std::string ChainName;
332 void emitCheck(const std::string &S) {
334 GeneratedCode.push_back(std::make_pair(1, S));
336 void emitCode(const std::string &S) {
338 GeneratedCode.push_back(std::make_pair(0, S));
340 void emitInit(const std::string &S) {
342 GeneratedCode.push_back(std::make_pair(2, S));
344 void emitDecl(const std::string &S) {
345 assert(!S.empty() && "Invalid declaration");
346 GeneratedDecl.insert(S);
348 void emitOpcode(const std::string &Opc) {
349 TargetOpcodes.push_back(Opc);
352 void emitVT(const std::string &VT) {
353 TargetVTs.push_back(VT);
357 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
358 TreePatternNode *pattern, TreePatternNode *instr,
359 std::vector<std::pair<unsigned, std::string> > &gc,
360 std::set<std::string> &gd,
361 std::vector<std::string> &to,
362 std::vector<std::string> &tv)
363 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
364 GeneratedCode(gc), GeneratedDecl(gd),
365 TargetOpcodes(to), TargetVTs(tv),
366 TmpNo(0), OpcNo(0), VTNo(0) {}
368 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
369 /// if the match fails. At this point, we already know that the opcode for N
370 /// matches, and the SDNode for the result has the RootName specified name.
371 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
372 const std::string &RootName, const std::string &ChainSuffix,
374 bool isRoot = (P == NULL);
375 // Emit instruction predicates. Each predicate is just a string for now.
377 std::string PredicateCheck;
378 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
379 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
380 Record *Def = Pred->getDef();
381 if (!Def->isSubClassOf("Predicate")) {
385 assert(0 && "Unknown predicate type!");
387 if (!PredicateCheck.empty())
388 PredicateCheck += " && ";
389 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
393 emitCheck(PredicateCheck);
397 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
398 emitCheck("cast<ConstantSDNode>(" + RootName +
399 ")->getSignExtended() == " + itostr(II->getValue()));
401 } else if (!NodeIsComplexPattern(N)) {
402 assert(0 && "Cannot match this as a leaf value!");
407 // If this node has a name associated with it, capture it in VariableMap. If
408 // we already saw this in the pattern, emit code to verify dagness.
409 if (!N->getName().empty()) {
410 std::string &VarMapEntry = VariableMap[N->getName()];
411 if (VarMapEntry.empty()) {
412 VarMapEntry = RootName;
414 // If we get here, this is a second reference to a specific name. Since
415 // we already have checked that the first reference is valid, we don't
416 // have to recursively match it, just check that it's the same as the
417 // previously named thing.
418 emitCheck(VarMapEntry + " == " + RootName);
423 OperatorMap[N->getName()] = N->getOperator();
427 // Emit code to load the child nodes and match their contents recursively.
429 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
430 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
431 bool EmittedUseCheck = false;
436 // Multiple uses of actual result?
437 emitCheck(RootName + ".hasOneUse()");
438 EmittedUseCheck = true;
440 // If the immediate use can somehow reach this node through another
441 // path, then can't fold it either or it will create a cycle.
442 // e.g. In the following diagram, XX can reach ld through YY. If
443 // ld is folded into XX, then YY is both a predecessor and a successor
453 bool NeedCheck = false;
457 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
459 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
460 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
461 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
462 PInfo.getNumOperands() > 1 ||
463 PInfo.hasProperty(SDNPHasChain) ||
464 PInfo.hasProperty(SDNPInFlag) ||
465 PInfo.hasProperty(SDNPOptInFlag);
469 std::string ParentName(RootName.begin(), RootName.end()-1);
470 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
478 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
479 "IsChainCompatible(" + ChainName + ".Val, " +
480 RootName + ".Val))");
481 OrigChains.push_back(std::make_pair(ChainName, RootName));
484 ChainName = "Chain" + ChainSuffix;
485 emitInit("SDOperand " + ChainName + " = " + RootName +
490 // Don't fold any node which reads or writes a flag and has multiple uses.
491 // FIXME: We really need to separate the concepts of flag and "glue". Those
492 // real flag results, e.g. X86CMP output, can have multiple uses.
493 // FIXME: If the optional incoming flag does not exist. Then it is ok to
496 (PatternHasProperty(N, SDNPInFlag, CGP) ||
497 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
498 PatternHasProperty(N, SDNPOutFlag, CGP))) {
499 if (!EmittedUseCheck) {
500 // Multiple uses of actual result?
501 emitCheck(RootName + ".hasOneUse()");
505 // If there is a node predicate for this, emit the call.
506 if (!N->getPredicateFn().empty())
507 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
510 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
511 // a constant without a predicate fn that has more that one bit set, handle
512 // this as a special case. This is usually for targets that have special
513 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
514 // handling stuff). Using these instructions is often far more efficient
515 // than materializing the constant. Unfortunately, both the instcombiner
516 // and the dag combiner can often infer that bits are dead, and thus drop
517 // them from the mask in the dag. For example, it might turn 'AND X, 255'
518 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
521 (N->getOperator()->getName() == "and" ||
522 N->getOperator()->getName() == "or") &&
523 N->getChild(1)->isLeaf() &&
524 N->getChild(1)->getPredicateFn().empty()) {
525 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
526 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
527 emitInit("SDOperand " + RootName + "0" + " = " +
528 RootName + ".getOperand(" + utostr(0) + ");");
529 emitInit("SDOperand " + RootName + "1" + " = " +
530 RootName + ".getOperand(" + utostr(1) + ");");
532 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
533 const char *MaskPredicate = N->getOperator()->getName() == "or"
534 ? "CheckOrMask(" : "CheckAndMask(";
535 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
536 RootName + "1), " + itostr(II->getValue()) + ")");
538 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
539 ChainSuffix + utostr(0), FoundChain);
545 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
546 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
547 RootName + ".getOperand(" +utostr(OpNo) + ");");
549 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
550 ChainSuffix + utostr(OpNo), FoundChain);
553 // Handle cases when root is a complex pattern.
554 const ComplexPattern *CP;
555 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
556 std::string Fn = CP->getSelectFunc();
557 unsigned NumOps = CP->getNumOperands();
558 for (unsigned i = 0; i < NumOps; ++i) {
559 emitDecl("CPTmp" + utostr(i));
560 emitCode("SDOperand CPTmp" + utostr(i) + ";");
562 if (CP->hasProperty(SDNPHasChain)) {
563 emitDecl("CPInChain");
564 emitDecl("Chain" + ChainSuffix);
565 emitCode("SDOperand CPInChain;");
566 emitCode("SDOperand Chain" + ChainSuffix + ";");
569 std::string Code = Fn + "(" + RootName + ", " + RootName;
570 for (unsigned i = 0; i < NumOps; i++)
571 Code += ", CPTmp" + utostr(i);
572 if (CP->hasProperty(SDNPHasChain)) {
573 ChainName = "Chain" + ChainSuffix;
574 Code += ", CPInChain, Chain" + ChainSuffix;
576 emitCheck(Code + ")");
580 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
581 const std::string &RootName,
582 const std::string &ParentRootName,
583 const std::string &ChainSuffix, bool &FoundChain) {
584 if (!Child->isLeaf()) {
585 // If it's not a leaf, recursively match.
586 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
587 emitCheck(RootName + ".getOpcode() == " +
588 CInfo.getEnumName());
589 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
590 if (NodeHasProperty(Child, SDNPHasChain, CGP))
591 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
593 // If this child has a name associated with it, capture it in VarMap. If
594 // we already saw this in the pattern, emit code to verify dagness.
595 if (!Child->getName().empty()) {
596 std::string &VarMapEntry = VariableMap[Child->getName()];
597 if (VarMapEntry.empty()) {
598 VarMapEntry = RootName;
600 // If we get here, this is a second reference to a specific name.
601 // Since we already have checked that the first reference is valid,
602 // we don't have to recursively match it, just check that it's the
603 // same as the previously named thing.
604 emitCheck(VarMapEntry + " == " + RootName);
605 Duplicates.insert(RootName);
610 // Handle leaves of various types.
611 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
612 Record *LeafRec = DI->getDef();
613 if (LeafRec->isSubClassOf("RegisterClass") ||
614 LeafRec->getName() == "ptr_rc") {
615 // Handle register references. Nothing to do here.
616 } else if (LeafRec->isSubClassOf("Register")) {
617 // Handle register references.
618 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
619 // Handle complex pattern.
620 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
621 std::string Fn = CP->getSelectFunc();
622 unsigned NumOps = CP->getNumOperands();
623 for (unsigned i = 0; i < NumOps; ++i) {
624 emitDecl("CPTmp" + utostr(i));
625 emitCode("SDOperand CPTmp" + utostr(i) + ";");
627 if (CP->hasProperty(SDNPHasChain)) {
628 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
629 FoldedChains.push_back(std::make_pair("CPInChain",
630 PInfo.getNumResults()));
631 ChainName = "Chain" + ChainSuffix;
632 emitDecl("CPInChain");
634 emitCode("SDOperand CPInChain;");
635 emitCode("SDOperand " + ChainName + ";");
638 std::string Code = Fn + "(";
639 if (CP->hasAttribute(CPAttrParentAsRoot)) {
640 Code += ParentRootName + ", ";
644 if (CP->hasProperty(SDNPHasChain)) {
645 std::string ParentName(RootName.begin(), RootName.end()-1);
646 Code += ParentName + ", ";
649 for (unsigned i = 0; i < NumOps; i++)
650 Code += ", CPTmp" + utostr(i);
651 if (CP->hasProperty(SDNPHasChain))
652 Code += ", CPInChain, Chain" + ChainSuffix;
653 emitCheck(Code + ")");
654 } else if (LeafRec->getName() == "srcvalue") {
655 // Place holder for SRCVALUE nodes. Nothing to do here.
656 } else if (LeafRec->isSubClassOf("ValueType")) {
657 // Make sure this is the specified value type.
658 emitCheck("cast<VTSDNode>(" + RootName +
659 ")->getVT() == MVT::" + LeafRec->getName());
660 } else if (LeafRec->isSubClassOf("CondCode")) {
661 // Make sure this is the specified cond code.
662 emitCheck("cast<CondCodeSDNode>(" + RootName +
663 ")->get() == ISD::" + LeafRec->getName());
669 assert(0 && "Unknown leaf type!");
672 // If there is a node predicate for this, emit the call.
673 if (!Child->getPredicateFn().empty())
674 emitCheck(Child->getPredicateFn() + "(" + RootName +
676 } else if (IntInit *II =
677 dynamic_cast<IntInit*>(Child->getLeafValue())) {
678 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
679 unsigned CTmp = TmpNo++;
680 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
681 RootName + ")->getSignExtended();");
683 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
688 assert(0 && "Unknown leaf type!");
693 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
694 /// we actually have to build a DAG!
695 std::vector<std::string>
696 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
697 bool InFlagDecled, bool ResNodeDecled,
698 bool LikeLeaf = false, bool isRoot = false) {
699 // List of arguments of getTargetNode() or SelectNodeTo().
700 std::vector<std::string> NodeOps;
701 // This is something selected from the pattern we matched.
702 if (!N->getName().empty()) {
703 const std::string &VarName = N->getName();
704 std::string Val = VariableMap[VarName];
705 bool ModifiedVal = false;
706 assert(!Val.empty() &&
707 "Variable referenced but not defined and not caught earlier!");
708 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
709 // Already selected this operand, just return the tmpval.
710 NodeOps.push_back(Val);
714 const ComplexPattern *CP;
715 unsigned ResNo = TmpNo++;
716 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
717 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
718 std::string CastType;
719 std::string TmpVar = "Tmp" + utostr(ResNo);
720 switch (N->getTypeNum(0)) {
722 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
723 << " type as an immediate constant. Aborting\n";
725 case MVT::i1: CastType = "bool"; break;
726 case MVT::i8: CastType = "unsigned char"; break;
727 case MVT::i16: CastType = "unsigned short"; break;
728 case MVT::i32: CastType = "unsigned"; break;
729 case MVT::i64: CastType = "uint64_t"; break;
731 emitCode("SDOperand " + TmpVar +
732 " = CurDAG->getTargetConstant(((" + CastType +
733 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
734 getEnumName(N->getTypeNum(0)) + ");");
735 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
736 // value if used multiple times by this pattern result.
739 NodeOps.push_back(Val);
740 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
741 Record *Op = OperatorMap[N->getName()];
742 // Transform ExternalSymbol to TargetExternalSymbol
743 if (Op && Op->getName() == "externalsym") {
744 std::string TmpVar = "Tmp"+utostr(ResNo);
745 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
746 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
747 Val + ")->getSymbol(), " +
748 getEnumName(N->getTypeNum(0)) + ");");
749 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
750 // this value if used multiple times by this pattern result.
754 NodeOps.push_back(Val);
755 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
756 || N->getOperator()->getName() == "tglobaltlsaddr")) {
757 Record *Op = OperatorMap[N->getName()];
758 // Transform GlobalAddress to TargetGlobalAddress
759 if (Op && (Op->getName() == "globaladdr" ||
760 Op->getName() == "globaltlsaddr")) {
761 std::string TmpVar = "Tmp" + utostr(ResNo);
762 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
763 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
764 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
766 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
767 // this value if used multiple times by this pattern result.
771 NodeOps.push_back(Val);
772 } else if (!N->isLeaf()
773 && (N->getOperator()->getName() == "texternalsym"
774 || N->getOperator()->getName() == "tconstpool")) {
775 // Do not rewrite the variable name, since we don't generate a new
777 NodeOps.push_back(Val);
778 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
779 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
780 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
781 NodeOps.push_back("CPTmp" + utostr(i));
784 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
785 // node even if it isn't one. Don't select it.
787 emitCode("AddToISelQueue(" + Val + ");");
788 if (isRoot && N->isLeaf()) {
789 emitCode("ReplaceUses(N, " + Val + ");");
790 emitCode("return NULL;");
793 NodeOps.push_back(Val);
797 VariableMap[VarName] = Val;
802 // If this is an explicit register reference, handle it.
803 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
804 unsigned ResNo = TmpNo++;
805 if (DI->getDef()->isSubClassOf("Register")) {
806 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
807 getQualifiedName(DI->getDef()) + ", " +
808 getEnumName(N->getTypeNum(0)) + ");");
809 NodeOps.push_back("Tmp" + utostr(ResNo));
811 } else if (DI->getDef()->getName() == "zero_reg") {
812 emitCode("SDOperand Tmp" + utostr(ResNo) +
813 " = CurDAG->getRegister(0, " +
814 getEnumName(N->getTypeNum(0)) + ");");
815 NodeOps.push_back("Tmp" + utostr(ResNo));
818 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
819 unsigned ResNo = TmpNo++;
820 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
821 emitCode("SDOperand Tmp" + utostr(ResNo) +
822 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
823 ", " + getEnumName(N->getTypeNum(0)) + ");");
824 NodeOps.push_back("Tmp" + utostr(ResNo));
831 assert(0 && "Unknown leaf type!");
835 Record *Op = N->getOperator();
836 if (Op->isSubClassOf("Instruction")) {
837 const CodeGenTarget &CGT = CGP.getTargetInfo();
838 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
839 const DAGInstruction &Inst = CGP.getInstruction(Op);
840 const TreePattern *InstPat = Inst.getPattern();
841 // FIXME: Assume actual pattern comes before "implicit".
842 TreePatternNode *InstPatNode =
843 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
844 : (InstPat ? InstPat->getTree(0) : NULL);
845 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
846 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
848 bool HasVarOps = isRoot && II.isVariadic;
849 // FIXME: fix how we deal with physical register operands.
850 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
851 bool HasImpResults = isRoot && DstRegs.size() > 0;
852 bool NodeHasOptInFlag = isRoot &&
853 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
854 bool NodeHasInFlag = isRoot &&
855 PatternHasProperty(Pattern, SDNPInFlag, CGP);
856 bool NodeHasOutFlag = isRoot &&
857 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
858 bool NodeHasChain = InstPatNode &&
859 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
860 bool InputHasChain = isRoot &&
861 NodeHasProperty(Pattern, SDNPHasChain, CGP);
862 unsigned NumResults = Inst.getNumResults();
863 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
865 if (NodeHasOptInFlag) {
866 emitCode("bool HasInFlag = "
867 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
870 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
872 // How many results is this pattern expected to produce?
873 unsigned NumPatResults = 0;
874 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
875 MVT::ValueType VT = Pattern->getTypeNum(i);
876 if (VT != MVT::isVoid && VT != MVT::Flag)
880 if (OrigChains.size() > 0) {
881 // The original input chain is being ignored. If it is not just
882 // pointing to the op that's being folded, we should create a
883 // TokenFactor with it and the chain of the folded op as the new chain.
884 // We could potentially be doing multiple levels of folding, in that
885 // case, the TokenFactor can have more operands.
886 emitCode("SmallVector<SDOperand, 8> InChains;");
887 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
888 emitCode("if (" + OrigChains[i].first + ".Val != " +
889 OrigChains[i].second + ".Val) {");
890 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
891 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
894 emitCode("AddToISelQueue(" + ChainName + ");");
895 emitCode("InChains.push_back(" + ChainName + ");");
896 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
897 "&InChains[0], InChains.size());");
900 // Loop over all of the operands of the instruction pattern, emitting code
901 // to fill them all in. The node 'N' usually has number children equal to
902 // the number of input operands of the instruction. However, in cases
903 // where there are predicate operands for an instruction, we need to fill
904 // in the 'execute always' values. Match up the node operands to the
905 // instruction operands to do this.
906 std::vector<std::string> AllOps;
907 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
908 for (unsigned ChildNo = 0, InstOpNo = NumResults;
909 InstOpNo != II.OperandList.size(); ++InstOpNo) {
910 std::vector<std::string> Ops;
912 // If this is a normal operand or a predicate operand without
913 // 'execute always', emit it.
914 Record *OperandNode = II.OperandList[InstOpNo].Rec;
915 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
916 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
917 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
918 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
919 InFlagDecled, ResNodeDecled);
920 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
923 // Otherwise, this is a predicate or optional def operand, emit the
924 // 'default ops' operands.
925 const DAGDefaultOperand &DefaultOp =
926 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
927 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
928 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
929 InFlagDecled, ResNodeDecled);
930 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
931 NumEAInputs += Ops.size();
936 // Emit all the chain and CopyToReg stuff.
937 bool ChainEmitted = NodeHasChain;
939 emitCode("AddToISelQueue(" + ChainName + ");");
940 if (NodeHasInFlag || HasImpInputs)
941 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
942 InFlagDecled, ResNodeDecled, true);
943 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
945 emitCode("SDOperand InFlag(0, 0);");
948 if (NodeHasOptInFlag) {
949 emitCode("if (HasInFlag) {");
950 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
951 emitCode(" AddToISelQueue(InFlag);");
956 unsigned ResNo = TmpNo++;
957 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
958 NodeHasOptInFlag || HasImpResults) {
961 std::string NodeName;
963 NodeName = "Tmp" + utostr(ResNo);
964 Code2 = "SDOperand " + NodeName + "(";
966 NodeName = "ResNode";
967 if (!ResNodeDecled) {
968 Code2 = "SDNode *" + NodeName + " = ";
969 ResNodeDecled = true;
971 Code2 = NodeName + " = ";
974 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
975 unsigned OpsNo = OpcNo;
976 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
978 // Output order: results, chain, flags
980 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
981 Code += ", VT" + utostr(VTNo);
982 emitVT(getEnumName(N->getTypeNum(0)));
984 // Add types for implicit results in physical registers, scheduler will
985 // care of adding copyfromreg nodes.
986 for (unsigned i = 0; i < NumDstRegs; i++) {
987 Record *RR = DstRegs[i];
988 if (RR->isSubClassOf("Register")) {
989 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
990 Code += ", " + getEnumName(RVT);
994 Code += ", MVT::Other";
996 Code += ", MVT::Flag";
998 // Figure out how many fixed inputs the node has. This is important to
999 // know which inputs are the variable ones if present.
1000 unsigned NumInputs = AllOps.size();
1001 NumInputs += NodeHasChain;
1005 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1006 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1011 // Figure out whether any operands at the end of the op list are not
1012 // part of the variable section.
1013 std::string EndAdjust;
1014 if (NodeHasInFlag || HasImpInputs)
1015 EndAdjust = "-1"; // Always has one flag.
1016 else if (NodeHasOptInFlag)
1017 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1019 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1020 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1022 emitCode(" AddToISelQueue(N.getOperand(i));");
1023 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1029 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1031 AllOps.push_back(ChainName);
1035 if (NodeHasInFlag || HasImpInputs)
1036 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1037 else if (NodeHasOptInFlag) {
1038 emitCode("if (HasInFlag)");
1039 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1041 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1043 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1044 AllOps.push_back("InFlag");
1046 unsigned NumOps = AllOps.size();
1048 if (!NodeHasOptInFlag && NumOps < 4) {
1049 for (unsigned i = 0; i != NumOps; ++i)
1050 Code += ", " + AllOps[i];
1052 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1053 for (unsigned i = 0; i != NumOps; ++i) {
1054 OpsCode += AllOps[i];
1058 emitCode(OpsCode + " };");
1059 Code += ", Ops" + utostr(OpsNo) + ", ";
1060 if (NodeHasOptInFlag) {
1061 Code += "HasInFlag ? ";
1062 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1064 Code += utostr(NumOps);
1070 emitCode(Code2 + Code + ");");
1073 // Remember which op produces the chain.
1075 emitCode(ChainName + " = SDOperand(" + NodeName +
1076 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
1078 emitCode(ChainName + " = SDOperand(" + NodeName +
1079 ", " + utostr(NumResults+NumDstRegs) + ");");
1082 NodeOps.push_back("Tmp" + utostr(ResNo));
1086 bool NeedReplace = false;
1087 if (NodeHasOutFlag) {
1088 if (!InFlagDecled) {
1089 emitCode("SDOperand InFlag(ResNode, " +
1090 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1091 InFlagDecled = true;
1093 emitCode("InFlag = SDOperand(ResNode, " +
1094 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1097 if (FoldedChains.size() > 0) {
1099 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1100 emitCode("ReplaceUses(SDOperand(" +
1101 FoldedChains[j].first + ".Val, " +
1102 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1103 utostr(NumResults+NumDstRegs) + "));");
1107 if (NodeHasOutFlag) {
1108 emitCode("ReplaceUses(SDOperand(N.Val, " +
1109 utostr(NumPatResults + (unsigned)InputHasChain)
1114 if (NeedReplace && InputHasChain)
1115 emitCode("ReplaceUses(SDOperand(N.Val, " +
1116 utostr(NumPatResults) + "), SDOperand(" + ChainName
1117 + ".Val, " + ChainName + ".ResNo" + "));");
1119 // User does not expect the instruction would produce a chain!
1120 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1122 } else if (InputHasChain && !NodeHasChain) {
1123 // One of the inner node produces a chain.
1125 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1126 "), SDOperand(ResNode, N.ResNo-1));");
1127 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1128 "), " + ChainName + ");");
1131 emitCode("return ResNode;");
1133 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1135 if (N->getTypeNum(0) != MVT::isVoid)
1136 Code += ", VT" + utostr(VTNo);
1138 Code += ", MVT::Flag";
1140 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1141 AllOps.push_back("InFlag");
1143 unsigned NumOps = AllOps.size();
1145 if (!NodeHasOptInFlag && NumOps < 4) {
1146 for (unsigned i = 0; i != NumOps; ++i)
1147 Code += ", " + AllOps[i];
1149 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1150 for (unsigned i = 0; i != NumOps; ++i) {
1151 OpsCode += AllOps[i];
1155 emitCode(OpsCode + " };");
1156 Code += ", Ops" + utostr(OpcNo) + ", ";
1157 Code += utostr(NumOps);
1160 emitCode(Code + ");");
1161 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1162 if (N->getTypeNum(0) != MVT::isVoid)
1163 emitVT(getEnumName(N->getTypeNum(0)));
1167 } else if (Op->isSubClassOf("SDNodeXForm")) {
1168 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1169 // PatLeaf node - the operand may or may not be a leaf node. But it should
1171 std::vector<std::string> Ops =
1172 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1173 ResNodeDecled, true);
1174 unsigned ResNo = TmpNo++;
1175 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1176 + "(" + Ops.back() + ".Val);");
1177 NodeOps.push_back("Tmp" + utostr(ResNo));
1179 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1184 throw std::string("Unknown node in result pattern!");
1188 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1189 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1190 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1191 /// for, this returns true otherwise false if Pat has all types.
1192 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1193 const std::string &Prefix, bool isRoot = false) {
1195 if (Pat->getExtTypes() != Other->getExtTypes()) {
1196 // Move a type over from 'other' to 'pat'.
1197 Pat->setTypes(Other->getExtTypes());
1198 // The top level node type is checked outside of the select function.
1200 emitCheck(Prefix + ".Val->getValueType(0) == " +
1201 getName(Pat->getTypeNum(0)));
1206 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1207 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1208 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1209 Prefix + utostr(OpNo)))
1215 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1217 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1218 bool &ChainEmitted, bool &InFlagDecled,
1219 bool &ResNodeDecled, bool isRoot = false) {
1220 const CodeGenTarget &T = CGP.getTargetInfo();
1222 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1223 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1224 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1225 TreePatternNode *Child = N->getChild(i);
1226 if (!Child->isLeaf()) {
1227 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1228 InFlagDecled, ResNodeDecled);
1230 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1231 if (!Child->getName().empty()) {
1232 std::string Name = RootName + utostr(OpNo);
1233 if (Duplicates.find(Name) != Duplicates.end())
1234 // A duplicate! Do not emit a copy for this node.
1238 Record *RR = DI->getDef();
1239 if (RR->isSubClassOf("Register")) {
1240 MVT::ValueType RVT = getRegisterValueType(RR, T);
1241 if (RVT == MVT::Flag) {
1242 if (!InFlagDecled) {
1243 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1244 InFlagDecled = true;
1246 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1247 emitCode("AddToISelQueue(InFlag);");
1249 if (!ChainEmitted) {
1250 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1251 ChainName = "Chain";
1252 ChainEmitted = true;
1254 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1255 if (!InFlagDecled) {
1256 emitCode("SDOperand InFlag(0, 0);");
1257 InFlagDecled = true;
1259 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1260 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1261 ", " + getQualifiedName(RR) +
1262 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1263 ResNodeDecled = true;
1264 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1265 emitCode("InFlag = SDOperand(ResNode, 1);");
1273 if (!InFlagDecled) {
1274 emitCode("SDOperand InFlag = " + RootName +
1275 ".getOperand(" + utostr(OpNo) + ");");
1276 InFlagDecled = true;
1278 emitCode("InFlag = " + RootName +
1279 ".getOperand(" + utostr(OpNo) + ");");
1280 emitCode("AddToISelQueue(InFlag);");
1285 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1286 /// stream to match the pattern, and generate the code for the match if it
1287 /// succeeds. Returns true if the pattern is not guaranteed to match.
1288 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1289 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1290 std::set<std::string> &GeneratedDecl,
1291 std::vector<std::string> &TargetOpcodes,
1292 std::vector<std::string> &TargetVTs) {
1293 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1294 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1295 GeneratedCode, GeneratedDecl,
1296 TargetOpcodes, TargetVTs);
1298 // Emit the matcher, capturing named arguments in VariableMap.
1299 bool FoundChain = false;
1300 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1302 // TP - Get *SOME* tree pattern, we don't care which.
1303 TreePattern &TP = *CGP.pf_begin()->second;
1305 // At this point, we know that we structurally match the pattern, but the
1306 // types of the nodes may not match. Figure out the fewest number of type
1307 // comparisons we need to emit. For example, if there is only one integer
1308 // type supported by a target, there should be no type comparisons at all for
1309 // integer patterns!
1311 // To figure out the fewest number of type checks needed, clone the pattern,
1312 // remove the types, then perform type inference on the pattern as a whole.
1313 // If there are unresolved types, emit an explicit check for those types,
1314 // apply the type to the tree, then rerun type inference. Iterate until all
1315 // types are resolved.
1317 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1318 RemoveAllTypes(Pat);
1321 // Resolve/propagate as many types as possible.
1323 bool MadeChange = true;
1325 MadeChange = Pat->ApplyTypeConstraints(TP,
1326 true/*Ignore reg constraints*/);
1328 assert(0 && "Error: could not find consistent types for something we"
1329 " already decided was ok!");
1333 // Insert a check for an unresolved type and add it to the tree. If we find
1334 // an unresolved type to add a check for, this returns true and we iterate,
1335 // otherwise we are done.
1336 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1338 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1339 false, false, false, true);
1343 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1344 /// a line causes any of them to be empty, remove them and return true when
1346 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1347 std::vector<std::pair<unsigned, std::string> > > >
1349 bool ErasedPatterns = false;
1350 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1351 Patterns[i].second.pop_back();
1352 if (Patterns[i].second.empty()) {
1353 Patterns.erase(Patterns.begin()+i);
1355 ErasedPatterns = true;
1358 return ErasedPatterns;
1361 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1362 /// code together between the patterns.
1363 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1364 std::vector<std::pair<unsigned, std::string> > > >
1365 &Patterns, unsigned Indent,
1367 typedef std::pair<unsigned, std::string> CodeLine;
1368 typedef std::vector<CodeLine> CodeList;
1369 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1371 if (Patterns.empty()) return;
1373 // Figure out how many patterns share the next code line. Explicitly copy
1374 // FirstCodeLine so that we don't invalidate a reference when changing
1376 const CodeLine FirstCodeLine = Patterns.back().second.back();
1377 unsigned LastMatch = Patterns.size()-1;
1378 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1381 // If not all patterns share this line, split the list into two pieces. The
1382 // first chunk will use this line, the second chunk won't.
1383 if (LastMatch != 0) {
1384 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1385 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1387 // FIXME: Emit braces?
1388 if (Shared.size() == 1) {
1389 const PatternToMatch &Pattern = *Shared.back().first;
1390 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1391 Pattern.getSrcPattern()->print(OS);
1392 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1393 Pattern.getDstPattern()->print(OS);
1395 unsigned AddedComplexity = Pattern.getAddedComplexity();
1396 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1397 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1399 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1401 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1403 if (FirstCodeLine.first != 1) {
1404 OS << std::string(Indent, ' ') << "{\n";
1407 EmitPatterns(Shared, Indent, OS);
1408 if (FirstCodeLine.first != 1) {
1410 OS << std::string(Indent, ' ') << "}\n";
1413 if (Other.size() == 1) {
1414 const PatternToMatch &Pattern = *Other.back().first;
1415 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1416 Pattern.getSrcPattern()->print(OS);
1417 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1418 Pattern.getDstPattern()->print(OS);
1420 unsigned AddedComplexity = Pattern.getAddedComplexity();
1421 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1422 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1424 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1426 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1428 EmitPatterns(Other, Indent, OS);
1432 // Remove this code from all of the patterns that share it.
1433 bool ErasedPatterns = EraseCodeLine(Patterns);
1435 bool isPredicate = FirstCodeLine.first == 1;
1437 // Otherwise, every pattern in the list has this line. Emit it.
1440 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1442 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1444 // If the next code line is another predicate, and if all of the pattern
1445 // in this group share the same next line, emit it inline now. Do this
1446 // until we run out of common predicates.
1447 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1448 // Check that all of fhe patterns in Patterns end with the same predicate.
1449 bool AllEndWithSamePredicate = true;
1450 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1451 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1452 AllEndWithSamePredicate = false;
1455 // If all of the predicates aren't the same, we can't share them.
1456 if (!AllEndWithSamePredicate) break;
1458 // Otherwise we can. Emit it shared now.
1459 OS << " &&\n" << std::string(Indent+4, ' ')
1460 << Patterns.back().second.back().second;
1461 ErasedPatterns = EraseCodeLine(Patterns);
1468 EmitPatterns(Patterns, Indent, OS);
1471 OS << std::string(Indent-2, ' ') << "}\n";
1474 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
1475 return CGP.getSDNodeInfo(Op).getEnumName();
1478 static std::string getLegalCName(std::string OpName) {
1479 std::string::size_type pos = OpName.find("::");
1480 if (pos != std::string::npos)
1481 OpName.replace(pos, 2, "_");
1485 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1486 const CodeGenTarget &Target = CGP.getTargetInfo();
1488 // Get the namespace to insert instructions into. Make sure not to pick up
1489 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1490 // instruction or something.
1492 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1493 e = Target.inst_end(); i != e; ++i) {
1494 InstNS = i->second.Namespace;
1495 if (InstNS != "TargetInstrInfo")
1499 if (!InstNS.empty()) InstNS += "::";
1501 // Group the patterns by their top-level opcodes.
1502 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1503 // All unique target node emission functions.
1504 std::map<std::string, unsigned> EmitFunctions;
1505 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1506 E = CGP.ptm_end(); I != E; ++I) {
1507 const PatternToMatch &Pattern = *I;
1509 TreePatternNode *Node = Pattern.getSrcPattern();
1510 if (!Node->isLeaf()) {
1511 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1512 push_back(&Pattern);
1514 const ComplexPattern *CP;
1515 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1516 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1517 push_back(&Pattern);
1518 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1519 std::vector<Record*> OpNodes = CP->getRootNodes();
1520 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1521 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1522 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1526 cerr << "Unrecognized opcode '";
1528 cerr << "' on tree pattern '";
1529 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1535 // For each opcode, there might be multiple select functions, one per
1536 // ValueType of the node (or its first operand if it doesn't produce a
1537 // non-chain result.
1538 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1540 // Emit one Select_* method for each top-level opcode. We do this instead of
1541 // emitting one giant switch statement to support compilers where this will
1542 // result in the recursive functions taking less stack space.
1543 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1544 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1545 PBOI != E; ++PBOI) {
1546 const std::string &OpName = PBOI->first;
1547 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1548 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1550 // We want to emit all of the matching code now. However, we want to emit
1551 // the matches in order of minimal cost. Sort the patterns so the least
1552 // cost one is at the start.
1553 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1554 PatternSortingPredicate(CGP));
1556 // Split them into groups by type.
1557 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1558 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1559 const PatternToMatch *Pat = PatternsOfOp[i];
1560 TreePatternNode *SrcPat = Pat->getSrcPattern();
1561 MVT::ValueType VT = SrcPat->getTypeNum(0);
1562 std::map<MVT::ValueType,
1563 std::vector<const PatternToMatch*> >::iterator TI =
1564 PatternsByType.find(VT);
1565 if (TI != PatternsByType.end())
1566 TI->second.push_back(Pat);
1568 std::vector<const PatternToMatch*> PVec;
1569 PVec.push_back(Pat);
1570 PatternsByType.insert(std::make_pair(VT, PVec));
1574 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1575 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1577 MVT::ValueType OpVT = II->first;
1578 std::vector<const PatternToMatch*> &Patterns = II->second;
1579 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1580 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1582 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1583 std::vector<std::vector<std::string> > PatternOpcodes;
1584 std::vector<std::vector<std::string> > PatternVTs;
1585 std::vector<std::set<std::string> > PatternDecls;
1586 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1587 CodeList GeneratedCode;
1588 std::set<std::string> GeneratedDecl;
1589 std::vector<std::string> TargetOpcodes;
1590 std::vector<std::string> TargetVTs;
1591 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1592 TargetOpcodes, TargetVTs);
1593 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1594 PatternDecls.push_back(GeneratedDecl);
1595 PatternOpcodes.push_back(TargetOpcodes);
1596 PatternVTs.push_back(TargetVTs);
1599 // Scan the code to see if all of the patterns are reachable and if it is
1600 // possible that the last one might not match.
1601 bool mightNotMatch = true;
1602 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1603 CodeList &GeneratedCode = CodeForPatterns[i].second;
1604 mightNotMatch = false;
1606 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1607 if (GeneratedCode[j].first == 1) { // predicate.
1608 mightNotMatch = true;
1613 // If this pattern definitely matches, and if it isn't the last one, the
1614 // patterns after it CANNOT ever match. Error out.
1615 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1616 cerr << "Pattern '";
1617 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1618 cerr << "' is impossible to select!\n";
1623 // Factor target node emission code (emitted by EmitResultCode) into
1624 // separate functions. Uniquing and share them among all instruction
1625 // selection routines.
1626 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1627 CodeList &GeneratedCode = CodeForPatterns[i].second;
1628 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1629 std::vector<std::string> &TargetVTs = PatternVTs[i];
1630 std::set<std::string> Decls = PatternDecls[i];
1631 std::vector<std::string> AddedInits;
1632 int CodeSize = (int)GeneratedCode.size();
1634 for (int j = CodeSize-1; j >= 0; --j) {
1635 if (LastPred == -1 && GeneratedCode[j].first == 1)
1637 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1638 AddedInits.push_back(GeneratedCode[j].second);
1641 std::string CalleeCode = "(const SDOperand &N";
1642 std::string CallerCode = "(N";
1643 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1644 CalleeCode += ", unsigned Opc" + utostr(j);
1645 CallerCode += ", " + TargetOpcodes[j];
1647 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1648 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1649 CallerCode += ", " + TargetVTs[j];
1651 for (std::set<std::string>::iterator
1652 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1653 std::string Name = *I;
1654 CalleeCode += ", SDOperand &" + Name;
1655 CallerCode += ", " + Name;
1659 // Prevent emission routines from being inlined to reduce selection
1660 // routines stack frame sizes.
1661 CalleeCode += "DISABLE_INLINE ";
1662 CalleeCode += "{\n";
1664 for (std::vector<std::string>::const_reverse_iterator
1665 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1666 CalleeCode += " " + *I + "\n";
1668 for (int j = LastPred+1; j < CodeSize; ++j)
1669 CalleeCode += " " + GeneratedCode[j].second + "\n";
1670 for (int j = LastPred+1; j < CodeSize; ++j)
1671 GeneratedCode.pop_back();
1672 CalleeCode += "}\n";
1674 // Uniquing the emission routines.
1675 unsigned EmitFuncNum;
1676 std::map<std::string, unsigned>::iterator EFI =
1677 EmitFunctions.find(CalleeCode);
1678 if (EFI != EmitFunctions.end()) {
1679 EmitFuncNum = EFI->second;
1681 EmitFuncNum = EmitFunctions.size();
1682 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1683 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1686 // Replace the emission code within selection routines with calls to the
1687 // emission functions.
1688 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1689 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1693 std::string OpVTStr;
1694 if (OpVT == MVT::iPTR) {
1696 } else if (OpVT == MVT::isVoid) {
1697 // Nodes with a void result actually have a first result type of either
1698 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1699 // void to this case, we handle it specially here.
1701 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1703 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1704 OpcodeVTMap.find(OpName);
1705 if (OpVTI == OpcodeVTMap.end()) {
1706 std::vector<std::string> VTSet;
1707 VTSet.push_back(OpVTStr);
1708 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1710 OpVTI->second.push_back(OpVTStr);
1712 OS << "SDNode *Select_" << getLegalCName(OpName)
1713 << OpVTStr << "(const SDOperand &N) {\n";
1715 // Loop through and reverse all of the CodeList vectors, as we will be
1716 // accessing them from their logical front, but accessing the end of a
1717 // vector is more efficient.
1718 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1719 CodeList &GeneratedCode = CodeForPatterns[i].second;
1720 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1723 // Next, reverse the list of patterns itself for the same reason.
1724 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1726 // Emit all of the patterns now, grouped together to share code.
1727 EmitPatterns(CodeForPatterns, 2, OS);
1729 // If the last pattern has predicates (which could fail) emit code to
1730 // catch the case where nothing handles a pattern.
1731 if (mightNotMatch) {
1732 OS << " cerr << \"Cannot yet select: \";\n";
1733 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1734 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1735 OpName != "ISD::INTRINSIC_VOID") {
1736 OS << " N.Val->dump(CurDAG);\n";
1738 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1739 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1740 << " cerr << \"intrinsic %\"<< "
1741 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1743 OS << " cerr << '\\n';\n"
1745 << " return NULL;\n";
1751 // Emit boilerplate.
1752 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1753 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1754 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1756 << " // Ensure that the asm operands are themselves selected.\n"
1757 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1758 << " AddToISelQueue(Ops[j]);\n\n"
1760 << " std::vector<MVT::ValueType> VTs;\n"
1761 << " VTs.push_back(MVT::Other);\n"
1762 << " VTs.push_back(MVT::Flag);\n"
1763 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1765 << " return New.Val;\n"
1768 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1769 << " SDOperand Chain = N.getOperand(0);\n"
1770 << " SDOperand N1 = N.getOperand(1);\n"
1771 << " SDOperand N2 = N.getOperand(2);\n"
1772 << " unsigned C1 = cast<ConstantSDNode>(N1)->getValue();\n"
1773 << " unsigned C2 = cast<ConstantSDNode>(N2)->getValue();\n"
1774 << " SDOperand Tmp1 = CurDAG->getTargetConstant(C1, MVT::i32);\n"
1775 << " SDOperand Tmp2 = CurDAG->getTargetConstant(C2, MVT::i32);\n"
1776 << " AddToISelQueue(Chain);\n"
1777 << " SDOperand Ops[] = { Tmp1, Tmp2, Chain };\n"
1778 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1779 << " MVT::Other, Ops, 3);\n"
1782 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1783 << " SDOperand N0 = N.getOperand(0);\n"
1784 << " SDOperand N1 = N.getOperand(1);\n"
1785 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1786 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1787 << " AddToISelQueue(N0);\n"
1788 << " SDOperand Ops[] = { N0, Tmp };\n"
1789 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1790 << " N.getValueType(), Ops, 2);\n"
1793 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1794 << " SDOperand N0 = N.getOperand(0);\n"
1795 << " SDOperand N1 = N.getOperand(1);\n"
1796 << " SDOperand N2 = N.getOperand(2);\n"
1797 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1798 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1799 << " AddToISelQueue(N1);\n"
1800 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1801 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1802 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1803 << " N.getValueType(), Ops+1, 2);\n"
1805 << " AddToISelQueue(N0);\n"
1806 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1807 << " N.getValueType(), Ops, 3);\n"
1811 OS << "// The main instruction selector code.\n"
1812 << "SDNode *SelectCode(SDOperand N) {\n"
1813 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1814 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1815 << "INSTRUCTION_LIST_END)) {\n"
1816 << " return NULL; // Already selected.\n"
1818 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1819 << " switch (N.getOpcode()) {\n"
1820 << " default: break;\n"
1821 << " case ISD::EntryToken: // These leaves remain the same.\n"
1822 << " case ISD::BasicBlock:\n"
1823 << " case ISD::Register:\n"
1824 << " case ISD::HANDLENODE:\n"
1825 << " case ISD::TargetConstant:\n"
1826 << " case ISD::TargetConstantPool:\n"
1827 << " case ISD::TargetFrameIndex:\n"
1828 << " case ISD::TargetExternalSymbol:\n"
1829 << " case ISD::TargetJumpTable:\n"
1830 << " case ISD::TargetGlobalTLSAddress:\n"
1831 << " case ISD::TargetGlobalAddress: {\n"
1832 << " return NULL;\n"
1834 << " case ISD::AssertSext:\n"
1835 << " case ISD::AssertZext: {\n"
1836 << " AddToISelQueue(N.getOperand(0));\n"
1837 << " ReplaceUses(N, N.getOperand(0));\n"
1838 << " return NULL;\n"
1840 << " case ISD::TokenFactor:\n"
1841 << " case ISD::CopyFromReg:\n"
1842 << " case ISD::CopyToReg: {\n"
1843 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1844 << " AddToISelQueue(N.getOperand(i));\n"
1845 << " return NULL;\n"
1847 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1848 << " case ISD::LABEL: return Select_LABEL(N);\n"
1849 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1850 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1853 // Loop over all of the case statements, emiting a call to each method we
1855 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1856 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1857 PBOI != E; ++PBOI) {
1858 const std::string &OpName = PBOI->first;
1859 // Potentially multiple versions of select for this opcode. One for each
1860 // ValueType of the node (or its first true operand if it doesn't produce a
1862 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1863 OpcodeVTMap.find(OpName);
1864 std::vector<std::string> &OpVTs = OpVTI->second;
1865 OS << " case " << OpName << ": {\n";
1866 // Keep track of whether we see a pattern that has an iPtr result.
1867 bool HasPtrPattern = false;
1868 bool HasDefaultPattern = false;
1870 OS << " switch (NVT) {\n";
1871 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1872 std::string &VTStr = OpVTs[i];
1873 if (VTStr.empty()) {
1874 HasDefaultPattern = true;
1878 // If this is a match on iPTR: don't emit it directly, we need special
1880 if (VTStr == "_iPTR") {
1881 HasPtrPattern = true;
1884 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1885 << " return Select_" << getLegalCName(OpName)
1886 << VTStr << "(N);\n";
1888 OS << " default:\n";
1890 // If there is an iPTR result version of this pattern, emit it here.
1891 if (HasPtrPattern) {
1892 OS << " if (NVT == TLI.getPointerTy())\n";
1893 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1895 if (HasDefaultPattern) {
1896 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1904 OS << " } // end of big switch.\n\n"
1905 << " cerr << \"Cannot yet select: \";\n"
1906 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1907 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1908 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1909 << " N.Val->dump(CurDAG);\n"
1911 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1912 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1913 << " cerr << \"intrinsic %\"<< "
1914 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1916 << " cerr << '\\n';\n"
1918 << " return NULL;\n"
1922 void DAGISelEmitter::run(std::ostream &OS) {
1923 EmitSourceFileHeader("DAG Instruction Selector for the " +
1924 CGP.getTargetInfo().getName() + " target", OS);
1926 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1927 << "// *** instruction selector class. These functions are really "
1930 OS << "#include \"llvm/Support/Compiler.h\"\n";
1932 OS << "// Instruction selector priority queue:\n"
1933 << "std::vector<SDNode*> ISelQueue;\n";
1934 OS << "/// Keep track of nodes which have already been added to queue.\n"
1935 << "unsigned char *ISelQueued;\n";
1936 OS << "/// Keep track of nodes which have already been selected.\n"
1937 << "unsigned char *ISelSelected;\n";
1938 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1939 << "std::vector<SDNode*> ISelKilled;\n\n";
1941 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1942 OS << "/// not reach Op.\n";
1943 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1944 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1945 OS << " return true;\n";
1946 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1947 OS << " return false;\n";
1948 OS << " else if (Chain->getNumOperands() > 0) {\n";
1949 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1950 OS << " if (C0.getValueType() == MVT::Other)\n";
1951 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1953 OS << " return true;\n";
1956 OS << "/// Sorting functions for the selection queue.\n"
1957 << "struct isel_sort : public std::binary_function"
1958 << "<SDNode*, SDNode*, bool> {\n"
1959 << " bool operator()(const SDNode* left, const SDNode* right) "
1961 << " return (left->getNodeId() > right->getNodeId());\n"
1965 OS << "inline void setQueued(int Id) {\n";
1966 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1968 OS << "inline bool isQueued(int Id) {\n";
1969 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1971 OS << "inline void setSelected(int Id) {\n";
1972 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1974 OS << "inline bool isSelected(int Id) {\n";
1975 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1978 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1979 OS << " int Id = N.Val->getNodeId();\n";
1980 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1981 OS << " ISelQueue.push_back(N.Val);\n";
1982 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1983 OS << " setQueued(Id);\n";
1987 OS << "inline void RemoveKilled() {\n";
1988 OS << " unsigned NumKilled = ISelKilled.size();\n";
1989 OS << " if (NumKilled) {\n";
1990 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
1991 OS << " SDNode *Temp = ISelKilled[i];\n";
1992 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
1993 << "Temp), ISelQueue.end());\n";
1995 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1996 OS << " ISelKilled.clear();\n";
2000 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
2001 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
2002 OS << " setSelected(F.Val->getNodeId());\n";
2003 OS << " RemoveKilled();\n";
2005 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
2006 OS << " unsigned FNumVals = F->getNumValues();\n";
2007 OS << " unsigned TNumVals = T->getNumValues();\n";
2008 OS << " if (FNumVals != TNumVals) {\n";
2009 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2011 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
2012 << "SDOperand(T, i), &ISelKilled);\n";
2013 OS << " } else {\n";
2014 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2016 OS << " setSelected(F->getNodeId());\n";
2017 OS << " RemoveKilled();\n";
2020 OS << "// SelectRoot - Top level entry to DAG isel.\n";
2021 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2022 OS << " SelectRootInit();\n";
2023 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2024 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2025 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2026 OS << " memset(ISelQueued, 0, NumBytes);\n";
2027 OS << " memset(ISelSelected, 0, NumBytes);\n";
2029 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2030 << " // a reference to the root node, preventing it from being deleted,\n"
2031 << " // and tracking any changes of the root.\n"
2032 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2033 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2034 OS << " while (!ISelQueue.empty()) {\n";
2035 OS << " SDNode *Node = ISelQueue.front();\n";
2036 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2037 OS << " ISelQueue.pop_back();\n";
2038 OS << " if (!isSelected(Node->getNodeId())) {\n";
2039 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2040 OS << " if (ResNode != Node) {\n";
2041 OS << " if (ResNode)\n";
2042 OS << " ReplaceUses(Node, ResNode);\n";
2043 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2044 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2045 OS << " RemoveKilled();\n";
2051 OS << " delete[] ISelQueued;\n";
2052 OS << " ISelQueued = NULL;\n";
2053 OS << " delete[] ISelSelected;\n";
2054 OS << " ISelSelected = NULL;\n";
2055 OS << " return Dummy.getValue();\n";
2058 EmitNodeTransforms(OS);
2059 EmitPredicateFunctions(OS);
2061 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2062 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2064 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2065 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2069 // At this point, we have full information about the 'Patterns' we need to
2070 // parse, both implicitly from instructions as well as from explicit pattern
2071 // definitions. Emit the resultant instruction selector.
2072 EmitInstructionSelector(OS);