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 "Not a valid pattern node to size!");
61 unsigned Size = 3; // The node itself.
62 // If the root node is a ConstantSDNode, increases its size.
63 // e.g. (set R32:$dst, 0).
64 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
67 // FIXME: This is a hack to statically increase the priority of patterns
68 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
69 // Later we can allow complexity / cost for each pattern to be (optionally)
70 // specified. To get best possible pattern match we'll need to dynamically
71 // calculate the complexity of all patterns a dag can potentially map to.
72 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
74 Size += AM->getNumOperands() * 3;
76 // If this node has some predicate function that must match, it adds to the
77 // complexity of this node.
78 if (!P->getPredicateFn().empty())
81 // Count children in the count if they are also nodes.
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
83 TreePatternNode *Child = P->getChild(i);
84 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
85 Size += getPatternSize(Child, CGP);
86 else if (Child->isLeaf()) {
87 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
88 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
89 else if (NodeIsComplexPattern(Child))
90 Size += getPatternSize(Child, CGP);
91 else if (!Child->getPredicateFn().empty())
99 /// getResultPatternCost - Compute the number of instructions for this pattern.
100 /// This is a temporary hack. We should really include the instruction
101 /// latencies in this calculation.
102 static unsigned getResultPatternCost(TreePatternNode *P,
103 CodeGenDAGPatterns &CGP) {
104 if (P->isLeaf()) return 0;
107 Record *Op = P->getOperator();
108 if (Op->isSubClassOf("Instruction")) {
110 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
111 if (II.usesCustomDAGSchedInserter)
114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
115 Cost += getResultPatternCost(P->getChild(i), CGP);
119 /// getResultPatternCodeSize - Compute the code size of instructions for this
121 static unsigned getResultPatternSize(TreePatternNode *P,
122 CodeGenDAGPatterns &CGP) {
123 if (P->isLeaf()) return 0;
126 Record *Op = P->getOperator();
127 if (Op->isSubClassOf("Instruction")) {
128 Cost += Op->getValueAsInt("CodeSize");
130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
131 Cost += getResultPatternSize(P->getChild(i), CGP);
135 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
136 // In particular, we want to match maximal patterns first and lowest cost within
137 // a particular complexity first.
138 struct PatternSortingPredicate {
139 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
140 CodeGenDAGPatterns &CGP;
142 bool operator()(const PatternToMatch *LHS,
143 const PatternToMatch *RHS) {
144 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
145 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
146 LHSSize += LHS->getAddedComplexity();
147 RHSSize += RHS->getAddedComplexity();
148 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
149 if (LHSSize < RHSSize) return false;
151 // If the patterns have equal complexity, compare generated instruction cost
152 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
153 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
154 if (LHSCost < RHSCost) return true;
155 if (LHSCost > RHSCost) return false;
157 return getResultPatternSize(LHS->getDstPattern(), CGP) <
158 getResultPatternSize(RHS->getDstPattern(), CGP);
162 /// getRegisterValueType - Look up and return the first ValueType of specified
163 /// RegisterClass record
164 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
165 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
166 return RC->getValueTypeNum(0);
171 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
172 /// type information from it.
173 static void RemoveAllTypes(TreePatternNode *N) {
176 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
177 RemoveAllTypes(N->getChild(i));
180 /// NodeHasProperty - return true if TreePatternNode has the specified
182 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
183 CodeGenDAGPatterns &CGP) {
185 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
187 return CP->hasProperty(Property);
190 Record *Operator = N->getOperator();
191 if (!Operator->isSubClassOf("SDNode")) return false;
193 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
196 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
197 CodeGenDAGPatterns &CGP) {
198 if (NodeHasProperty(N, Property, CGP))
201 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
202 TreePatternNode *Child = N->getChild(i);
203 if (PatternHasProperty(Child, Property, CGP))
210 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
211 return CGP.getSDNodeInfo(Op).getEnumName();
215 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
216 bool isStore = !N->isLeaf() &&
217 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
218 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
221 bool HasChain = false;
222 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
223 TreePatternNode *Child = N->getChild(i);
224 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
232 //===----------------------------------------------------------------------===//
233 // Node Transformation emitter implementation.
235 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
236 // Walk the pattern fragments, adding them to a map, which sorts them by
238 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
239 NXsByNameTy NXsByName;
241 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
243 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
245 OS << "\n// Node transformations.\n";
247 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
249 Record *SDNode = I->second.first;
250 std::string Code = I->second.second;
252 if (Code.empty()) continue; // Empty code? Skip it.
254 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
255 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
257 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
259 if (ClassName != "SDNode")
260 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
261 OS << Code << "\n}\n";
265 //===----------------------------------------------------------------------===//
266 // Predicate emitter implementation.
269 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
270 OS << "\n// Predicate functions.\n";
272 // Walk the pattern fragments, adding them to a map, which sorts them by
274 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
275 PFsByNameTy PFsByName;
277 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
279 PFsByName.insert(std::make_pair(I->first->getName(), *I));
282 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
284 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
285 TreePattern *P = I->second.second;
287 // If there is a code init for this fragment, emit the predicate code.
288 std::string Code = PatFragRecord->getValueAsCode("Predicate");
289 if (Code.empty()) continue;
291 if (P->getOnlyTree()->isLeaf())
292 OS << "inline bool Predicate_" << PatFragRecord->getName()
293 << "(SDNode *N) {\n";
295 std::string ClassName =
296 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
297 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
299 OS << "inline bool Predicate_" << PatFragRecord->getName()
300 << "(SDNode *" << C2 << ") {\n";
301 if (ClassName != "SDNode")
302 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
304 OS << Code << "\n}\n";
311 //===----------------------------------------------------------------------===//
312 // PatternCodeEmitter implementation.
314 class PatternCodeEmitter {
316 CodeGenDAGPatterns &CGP;
319 ListInit *Predicates;
322 // Instruction selector pattern.
323 TreePatternNode *Pattern;
324 // Matched instruction.
325 TreePatternNode *Instruction;
327 // Node to name mapping
328 std::map<std::string, std::string> VariableMap;
329 // Node to operator mapping
330 std::map<std::string, Record*> OperatorMap;
331 // Name of the folded node which produces a flag.
332 std::pair<std::string, unsigned> FoldedFlag;
333 // Names of all the folded nodes which produce chains.
334 std::vector<std::pair<std::string, unsigned> > FoldedChains;
335 // Original input chain(s).
336 std::vector<std::pair<std::string, std::string> > OrigChains;
337 std::set<std::string> Duplicates;
339 /// LSI - Load/Store information.
340 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
341 /// for each memory access. This facilitates the use of AliasAnalysis in
343 std::vector<std::string> LSI;
345 /// GeneratedCode - This is the buffer that we emit code to. The first int
346 /// indicates whether this is an exit predicate (something that should be
347 /// tested, and if true, the match fails) [when 1], or normal code to emit
348 /// [when 0], or initialization code to emit [when 2].
349 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
350 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
351 /// the set of patterns for each top-level opcode.
352 std::set<std::string> &GeneratedDecl;
353 /// TargetOpcodes - The target specific opcodes used by the resulting
355 std::vector<std::string> &TargetOpcodes;
356 std::vector<std::string> &TargetVTs;
357 /// OutputIsVariadic - Records whether the instruction output pattern uses
358 /// variable_ops. This requires that the Emit function be passed an
359 /// additional argument to indicate where the input varargs operands
361 bool &OutputIsVariadic;
362 /// NumInputRootOps - Records the number of operands the root node of the
363 /// input pattern has. This information is used in the generated code to
364 /// pass to Emit functions when variable_ops processing is needed.
365 unsigned &NumInputRootOps;
367 std::string ChainName;
372 void emitCheck(const std::string &S) {
374 GeneratedCode.push_back(std::make_pair(1, S));
376 void emitCode(const std::string &S) {
378 GeneratedCode.push_back(std::make_pair(0, S));
380 void emitInit(const std::string &S) {
382 GeneratedCode.push_back(std::make_pair(2, S));
384 void emitDecl(const std::string &S) {
385 assert(!S.empty() && "Invalid declaration");
386 GeneratedDecl.insert(S);
388 void emitOpcode(const std::string &Opc) {
389 TargetOpcodes.push_back(Opc);
392 void emitVT(const std::string &VT) {
393 TargetVTs.push_back(VT);
397 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
398 TreePatternNode *pattern, TreePatternNode *instr,
399 std::vector<std::pair<unsigned, std::string> > &gc,
400 std::set<std::string> &gd,
401 std::vector<std::string> &to,
402 std::vector<std::string> &tv,
405 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
406 GeneratedCode(gc), GeneratedDecl(gd),
407 TargetOpcodes(to), TargetVTs(tv),
408 OutputIsVariadic(oiv), NumInputRootOps(niro),
409 TmpNo(0), OpcNo(0), VTNo(0) {}
411 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
412 /// if the match fails. At this point, we already know that the opcode for N
413 /// matches, and the SDNode for the result has the RootName specified name.
414 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
415 const std::string &RootName, const std::string &ChainSuffix,
418 // Save loads/stores matched by a pattern.
419 if (!N->isLeaf() && N->getName().empty()) {
420 if (NodeHasProperty(N, SDNPMemOperand, CGP))
421 LSI.push_back(RootName);
424 bool isRoot = (P == NULL);
425 // Emit instruction predicates. Each predicate is just a string for now.
427 // Record input varargs info.
428 NumInputRootOps = N->getNumChildren();
430 if (DisablePatternForFastISel(N, CGP))
431 emitCheck("!FastISel");
433 std::string PredicateCheck;
434 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
435 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
436 Record *Def = Pred->getDef();
437 if (!Def->isSubClassOf("Predicate")) {
441 assert(0 && "Unknown predicate type!");
443 if (!PredicateCheck.empty())
444 PredicateCheck += " && ";
445 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
449 emitCheck(PredicateCheck);
453 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
454 emitCheck("cast<ConstantSDNode>(" + RootName +
455 ")->getSignExtended() == " + itostr(II->getValue()));
457 } else if (!NodeIsComplexPattern(N)) {
458 assert(0 && "Cannot match this as a leaf value!");
463 // If this node has a name associated with it, capture it in VariableMap. If
464 // we already saw this in the pattern, emit code to verify dagness.
465 if (!N->getName().empty()) {
466 std::string &VarMapEntry = VariableMap[N->getName()];
467 if (VarMapEntry.empty()) {
468 VarMapEntry = RootName;
470 // If we get here, this is a second reference to a specific name. Since
471 // we already have checked that the first reference is valid, we don't
472 // have to recursively match it, just check that it's the same as the
473 // previously named thing.
474 emitCheck(VarMapEntry + " == " + RootName);
479 OperatorMap[N->getName()] = N->getOperator();
483 // Emit code to load the child nodes and match their contents recursively.
485 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
486 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
487 bool EmittedUseCheck = false;
492 // Multiple uses of actual result?
493 emitCheck(RootName + ".hasOneUse()");
494 EmittedUseCheck = true;
496 // If the immediate use can somehow reach this node through another
497 // path, then can't fold it either or it will create a cycle.
498 // e.g. In the following diagram, XX can reach ld through YY. If
499 // ld is folded into XX, then YY is both a predecessor and a successor
509 bool NeedCheck = P != Pattern;
511 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
513 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
514 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
515 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
516 PInfo.getNumOperands() > 1 ||
517 PInfo.hasProperty(SDNPHasChain) ||
518 PInfo.hasProperty(SDNPInFlag) ||
519 PInfo.hasProperty(SDNPOptInFlag);
523 std::string ParentName(RootName.begin(), RootName.end()-1);
524 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
532 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
533 "IsChainCompatible(" + ChainName + ".Val, " +
534 RootName + ".Val))");
535 OrigChains.push_back(std::make_pair(ChainName, RootName));
538 ChainName = "Chain" + ChainSuffix;
539 emitInit("SDOperand " + ChainName + " = " + RootName +
544 // Don't fold any node which reads or writes a flag and has multiple uses.
545 // FIXME: We really need to separate the concepts of flag and "glue". Those
546 // real flag results, e.g. X86CMP output, can have multiple uses.
547 // FIXME: If the optional incoming flag does not exist. Then it is ok to
550 (PatternHasProperty(N, SDNPInFlag, CGP) ||
551 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
552 PatternHasProperty(N, SDNPOutFlag, CGP))) {
553 if (!EmittedUseCheck) {
554 // Multiple uses of actual result?
555 emitCheck(RootName + ".hasOneUse()");
559 // If there is a node predicate for this, emit the call.
560 if (!N->getPredicateFn().empty())
561 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
564 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
565 // a constant without a predicate fn that has more that one bit set, handle
566 // this as a special case. This is usually for targets that have special
567 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
568 // handling stuff). Using these instructions is often far more efficient
569 // than materializing the constant. Unfortunately, both the instcombiner
570 // and the dag combiner can often infer that bits are dead, and thus drop
571 // them from the mask in the dag. For example, it might turn 'AND X, 255'
572 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
575 (N->getOperator()->getName() == "and" ||
576 N->getOperator()->getName() == "or") &&
577 N->getChild(1)->isLeaf() &&
578 N->getChild(1)->getPredicateFn().empty()) {
579 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
580 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
581 emitInit("SDOperand " + RootName + "0" + " = " +
582 RootName + ".getOperand(" + utostr(0) + ");");
583 emitInit("SDOperand " + RootName + "1" + " = " +
584 RootName + ".getOperand(" + utostr(1) + ");");
586 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
587 const char *MaskPredicate = N->getOperator()->getName() == "or"
588 ? "CheckOrMask(" : "CheckAndMask(";
589 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
590 RootName + "1), " + itostr(II->getValue()) + ")");
592 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
593 ChainSuffix + utostr(0), FoundChain);
599 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
600 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
601 RootName + ".getOperand(" +utostr(OpNo) + ");");
603 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
604 ChainSuffix + utostr(OpNo), FoundChain);
607 // Handle cases when root is a complex pattern.
608 const ComplexPattern *CP;
609 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
610 std::string Fn = CP->getSelectFunc();
611 unsigned NumOps = CP->getNumOperands();
612 for (unsigned i = 0; i < NumOps; ++i) {
613 emitDecl("CPTmp" + utostr(i));
614 emitCode("SDOperand CPTmp" + utostr(i) + ";");
616 if (CP->hasProperty(SDNPHasChain)) {
617 emitDecl("CPInChain");
618 emitDecl("Chain" + ChainSuffix);
619 emitCode("SDOperand CPInChain;");
620 emitCode("SDOperand Chain" + ChainSuffix + ";");
623 std::string Code = Fn + "(" + RootName + ", " + RootName;
624 for (unsigned i = 0; i < NumOps; i++)
625 Code += ", CPTmp" + utostr(i);
626 if (CP->hasProperty(SDNPHasChain)) {
627 ChainName = "Chain" + ChainSuffix;
628 Code += ", CPInChain, Chain" + ChainSuffix;
630 emitCheck(Code + ")");
634 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
635 const std::string &RootName,
636 const std::string &ParentRootName,
637 const std::string &ChainSuffix, bool &FoundChain) {
638 if (!Child->isLeaf()) {
639 // If it's not a leaf, recursively match.
640 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
641 emitCheck(RootName + ".getOpcode() == " +
642 CInfo.getEnumName());
643 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
644 bool HasChain = false;
645 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
647 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
649 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
650 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
651 "Pattern folded multiple nodes which produce flags?");
652 FoldedFlag = std::make_pair(RootName,
653 CInfo.getNumResults() + (unsigned)HasChain);
656 // If this child has a name associated with it, capture it in VarMap. If
657 // we already saw this in the pattern, emit code to verify dagness.
658 if (!Child->getName().empty()) {
659 std::string &VarMapEntry = VariableMap[Child->getName()];
660 if (VarMapEntry.empty()) {
661 VarMapEntry = RootName;
663 // If we get here, this is a second reference to a specific name.
664 // Since we already have checked that the first reference is valid,
665 // we don't have to recursively match it, just check that it's the
666 // same as the previously named thing.
667 emitCheck(VarMapEntry + " == " + RootName);
668 Duplicates.insert(RootName);
673 // Handle leaves of various types.
674 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
675 Record *LeafRec = DI->getDef();
676 if (LeafRec->isSubClassOf("RegisterClass") ||
677 LeafRec->getName() == "ptr_rc") {
678 // Handle register references. Nothing to do here.
679 } else if (LeafRec->isSubClassOf("Register")) {
680 // Handle register references.
681 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
682 // Handle complex pattern.
683 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
684 std::string Fn = CP->getSelectFunc();
685 unsigned NumOps = CP->getNumOperands();
686 for (unsigned i = 0; i < NumOps; ++i) {
687 emitDecl("CPTmp" + utostr(i));
688 emitCode("SDOperand CPTmp" + utostr(i) + ";");
690 if (CP->hasProperty(SDNPHasChain)) {
691 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
692 FoldedChains.push_back(std::make_pair("CPInChain",
693 PInfo.getNumResults()));
694 ChainName = "Chain" + ChainSuffix;
695 emitDecl("CPInChain");
697 emitCode("SDOperand CPInChain;");
698 emitCode("SDOperand " + ChainName + ";");
701 std::string Code = Fn + "(";
702 if (CP->hasAttribute(CPAttrParentAsRoot)) {
703 Code += ParentRootName + ", ";
707 if (CP->hasProperty(SDNPHasChain)) {
708 std::string ParentName(RootName.begin(), RootName.end()-1);
709 Code += ParentName + ", ";
712 for (unsigned i = 0; i < NumOps; i++)
713 Code += ", CPTmp" + utostr(i);
714 if (CP->hasProperty(SDNPHasChain))
715 Code += ", CPInChain, Chain" + ChainSuffix;
716 emitCheck(Code + ")");
717 } else if (LeafRec->getName() == "srcvalue") {
718 // Place holder for SRCVALUE nodes. Nothing to do here.
719 } else if (LeafRec->isSubClassOf("ValueType")) {
720 // Make sure this is the specified value type.
721 emitCheck("cast<VTSDNode>(" + RootName +
722 ")->getVT() == MVT::" + LeafRec->getName());
723 } else if (LeafRec->isSubClassOf("CondCode")) {
724 // Make sure this is the specified cond code.
725 emitCheck("cast<CondCodeSDNode>(" + RootName +
726 ")->get() == ISD::" + LeafRec->getName());
732 assert(0 && "Unknown leaf type!");
735 // If there is a node predicate for this, emit the call.
736 if (!Child->getPredicateFn().empty())
737 emitCheck(Child->getPredicateFn() + "(" + RootName +
739 } else if (IntInit *II =
740 dynamic_cast<IntInit*>(Child->getLeafValue())) {
741 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
742 unsigned CTmp = TmpNo++;
743 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
744 RootName + ")->getSignExtended();");
746 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
751 assert(0 && "Unknown leaf type!");
756 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
757 /// we actually have to build a DAG!
758 std::vector<std::string>
759 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
760 bool InFlagDecled, bool ResNodeDecled,
761 bool LikeLeaf = false, bool isRoot = false) {
762 // List of arguments of getTargetNode() or SelectNodeTo().
763 std::vector<std::string> NodeOps;
764 // This is something selected from the pattern we matched.
765 if (!N->getName().empty()) {
766 const std::string &VarName = N->getName();
767 std::string Val = VariableMap[VarName];
768 bool ModifiedVal = false;
770 cerr << "Variable '" << VarName << " referenced but not defined "
771 << "and not caught earlier!\n";
774 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
775 // Already selected this operand, just return the tmpval.
776 NodeOps.push_back(Val);
780 const ComplexPattern *CP;
781 unsigned ResNo = TmpNo++;
782 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
783 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
784 std::string CastType;
785 std::string TmpVar = "Tmp" + utostr(ResNo);
786 switch (N->getTypeNum(0)) {
788 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
789 << " type as an immediate constant. Aborting\n";
791 case MVT::i1: CastType = "bool"; break;
792 case MVT::i8: CastType = "unsigned char"; break;
793 case MVT::i16: CastType = "unsigned short"; break;
794 case MVT::i32: CastType = "unsigned"; break;
795 case MVT::i64: CastType = "uint64_t"; break;
797 emitCode("SDOperand " + TmpVar +
798 " = CurDAG->getTargetConstant(((" + CastType +
799 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
800 getEnumName(N->getTypeNum(0)) + ");");
801 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
802 // value if used multiple times by this pattern result.
805 NodeOps.push_back(Val);
806 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
807 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
808 std::string TmpVar = "Tmp" + utostr(ResNo);
809 emitCode("SDOperand " + TmpVar +
810 " = CurDAG->getTargetConstantFP(cast<ConstantFPSDNode>(" +
811 Val + ")->getValueAPF(), cast<ConstantFPSDNode>(" + Val +
812 ")->getValueType(0));");
813 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
814 // value if used multiple times by this pattern result.
817 NodeOps.push_back(Val);
818 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
819 Record *Op = OperatorMap[N->getName()];
820 // Transform ExternalSymbol to TargetExternalSymbol
821 if (Op && Op->getName() == "externalsym") {
822 std::string TmpVar = "Tmp"+utostr(ResNo);
823 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
824 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
825 Val + ")->getSymbol(), " +
826 getEnumName(N->getTypeNum(0)) + ");");
827 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
828 // this value if used multiple times by this pattern result.
832 NodeOps.push_back(Val);
833 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
834 || N->getOperator()->getName() == "tglobaltlsaddr")) {
835 Record *Op = OperatorMap[N->getName()];
836 // Transform GlobalAddress to TargetGlobalAddress
837 if (Op && (Op->getName() == "globaladdr" ||
838 Op->getName() == "globaltlsaddr")) {
839 std::string TmpVar = "Tmp" + utostr(ResNo);
840 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
841 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
842 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
844 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
845 // this value if used multiple times by this pattern result.
849 NodeOps.push_back(Val);
850 } else if (!N->isLeaf()
851 && (N->getOperator()->getName() == "texternalsym"
852 || N->getOperator()->getName() == "tconstpool")) {
853 // Do not rewrite the variable name, since we don't generate a new
855 NodeOps.push_back(Val);
856 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
857 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
858 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
859 NodeOps.push_back("CPTmp" + utostr(i));
862 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
863 // node even if it isn't one. Don't select it.
865 emitCode("AddToISelQueue(" + Val + ");");
866 if (isRoot && N->isLeaf()) {
867 emitCode("ReplaceUses(N, " + Val + ");");
868 emitCode("return NULL;");
871 NodeOps.push_back(Val);
875 VariableMap[VarName] = Val;
880 // If this is an explicit register reference, handle it.
881 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
882 unsigned ResNo = TmpNo++;
883 if (DI->getDef()->isSubClassOf("Register")) {
884 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
885 getQualifiedName(DI->getDef()) + ", " +
886 getEnumName(N->getTypeNum(0)) + ");");
887 NodeOps.push_back("Tmp" + utostr(ResNo));
889 } else if (DI->getDef()->getName() == "zero_reg") {
890 emitCode("SDOperand Tmp" + utostr(ResNo) +
891 " = CurDAG->getRegister(0, " +
892 getEnumName(N->getTypeNum(0)) + ");");
893 NodeOps.push_back("Tmp" + utostr(ResNo));
896 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
897 unsigned ResNo = TmpNo++;
898 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
899 emitCode("SDOperand Tmp" + utostr(ResNo) +
900 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
901 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
902 NodeOps.push_back("Tmp" + utostr(ResNo));
909 assert(0 && "Unknown leaf type!");
913 Record *Op = N->getOperator();
914 if (Op->isSubClassOf("Instruction")) {
915 const CodeGenTarget &CGT = CGP.getTargetInfo();
916 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
917 const DAGInstruction &Inst = CGP.getInstruction(Op);
918 const TreePattern *InstPat = Inst.getPattern();
919 // FIXME: Assume actual pattern comes before "implicit".
920 TreePatternNode *InstPatNode =
921 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
922 : (InstPat ? InstPat->getTree(0) : NULL);
923 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
924 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
926 bool IsVariadic = isRoot && II.isVariadic;
927 // FIXME: fix how we deal with physical register operands.
928 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
929 bool HasImpResults = isRoot && DstRegs.size() > 0;
930 bool NodeHasOptInFlag = isRoot &&
931 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
932 bool NodeHasInFlag = isRoot &&
933 PatternHasProperty(Pattern, SDNPInFlag, CGP);
934 bool NodeHasOutFlag = isRoot &&
935 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
936 bool NodeHasChain = InstPatNode &&
937 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
938 bool InputHasChain = isRoot &&
939 NodeHasProperty(Pattern, SDNPHasChain, CGP);
940 unsigned NumResults = Inst.getNumResults();
941 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
943 // Record output varargs info.
944 OutputIsVariadic = IsVariadic;
946 if (NodeHasOptInFlag) {
947 emitCode("bool HasInFlag = "
948 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
951 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
953 // How many results is this pattern expected to produce?
954 unsigned NumPatResults = 0;
955 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
956 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
957 if (VT != MVT::isVoid && VT != MVT::Flag)
961 if (OrigChains.size() > 0) {
962 // The original input chain is being ignored. If it is not just
963 // pointing to the op that's being folded, we should create a
964 // TokenFactor with it and the chain of the folded op as the new chain.
965 // We could potentially be doing multiple levels of folding, in that
966 // case, the TokenFactor can have more operands.
967 emitCode("SmallVector<SDOperand, 8> InChains;");
968 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
969 emitCode("if (" + OrigChains[i].first + ".Val != " +
970 OrigChains[i].second + ".Val) {");
971 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
972 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
975 emitCode("AddToISelQueue(" + ChainName + ");");
976 emitCode("InChains.push_back(" + ChainName + ");");
977 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
978 "&InChains[0], InChains.size());");
981 // Loop over all of the operands of the instruction pattern, emitting code
982 // to fill them all in. The node 'N' usually has number children equal to
983 // the number of input operands of the instruction. However, in cases
984 // where there are predicate operands for an instruction, we need to fill
985 // in the 'execute always' values. Match up the node operands to the
986 // instruction operands to do this.
987 std::vector<std::string> AllOps;
988 for (unsigned ChildNo = 0, InstOpNo = NumResults;
989 InstOpNo != II.OperandList.size(); ++InstOpNo) {
990 std::vector<std::string> Ops;
992 // Determine what to emit for this operand.
993 Record *OperandNode = II.OperandList[InstOpNo].Rec;
994 if ((OperandNode->isSubClassOf("PredicateOperand") ||
995 OperandNode->isSubClassOf("OptionalDefOperand")) &&
996 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
997 // This is a predicate or optional def operand; emit the
998 // 'default ops' operands.
999 const DAGDefaultOperand &DefaultOp =
1000 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1001 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1002 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1003 InFlagDecled, ResNodeDecled);
1004 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1007 // Otherwise this is a normal operand or a predicate operand without
1008 // 'execute always'; emit it.
1009 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1010 InFlagDecled, ResNodeDecled);
1011 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1016 // Emit all the chain and CopyToReg stuff.
1017 bool ChainEmitted = NodeHasChain;
1019 emitCode("AddToISelQueue(" + ChainName + ");");
1020 if (NodeHasInFlag || HasImpInputs)
1021 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1022 InFlagDecled, ResNodeDecled, true);
1023 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1024 if (!InFlagDecled) {
1025 emitCode("SDOperand InFlag(0, 0);");
1026 InFlagDecled = true;
1028 if (NodeHasOptInFlag) {
1029 emitCode("if (HasInFlag) {");
1030 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1031 emitCode(" AddToISelQueue(InFlag);");
1036 unsigned ResNo = TmpNo++;
1038 unsigned OpsNo = OpcNo;
1039 std::string CodePrefix;
1040 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1041 std::deque<std::string> After;
1042 std::string NodeName;
1044 NodeName = "Tmp" + utostr(ResNo);
1045 CodePrefix = "SDOperand " + NodeName + "(";
1047 NodeName = "ResNode";
1048 if (!ResNodeDecled) {
1049 CodePrefix = "SDNode *" + NodeName + " = ";
1050 ResNodeDecled = true;
1052 CodePrefix = NodeName + " = ";
1055 std::string Code = "Opc" + utostr(OpcNo);
1057 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1059 // Output order: results, chain, flags
1061 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1062 Code += ", VT" + utostr(VTNo);
1063 emitVT(getEnumName(N->getTypeNum(0)));
1065 // Add types for implicit results in physical registers, scheduler will
1066 // care of adding copyfromreg nodes.
1067 for (unsigned i = 0; i < NumDstRegs; i++) {
1068 Record *RR = DstRegs[i];
1069 if (RR->isSubClassOf("Register")) {
1070 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1071 Code += ", " + getEnumName(RVT);
1075 Code += ", MVT::Other";
1077 Code += ", MVT::Flag";
1081 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1082 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1085 // Figure out whether any operands at the end of the op list are not
1086 // part of the variable section.
1087 std::string EndAdjust;
1088 if (NodeHasInFlag || HasImpInputs)
1089 EndAdjust = "-1"; // Always has one flag.
1090 else if (NodeHasOptInFlag)
1091 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1093 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1094 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1096 emitCode(" AddToISelQueue(N.getOperand(i));");
1097 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1101 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1103 if (II.isSimpleLoad | II.mayLoad | II.mayStore) {
1104 std::vector<std::string>::const_iterator mi, mie;
1105 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1106 emitCode("SDOperand LSI_" + *mi + " = "
1107 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1108 *mi + ")->getMemOperand());");
1110 emitCode("Ops" + utostr(OpsNo) + ".push_back(LSI_" + *mi + ");");
1112 AllOps.push_back("LSI_" + *mi);
1118 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1120 AllOps.push_back(ChainName);
1124 if (NodeHasInFlag || HasImpInputs)
1125 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1126 else if (NodeHasOptInFlag) {
1127 emitCode("if (HasInFlag)");
1128 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1130 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1132 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1133 AllOps.push_back("InFlag");
1135 unsigned NumOps = AllOps.size();
1137 if (!NodeHasOptInFlag && NumOps < 4) {
1138 for (unsigned i = 0; i != NumOps; ++i)
1139 Code += ", " + AllOps[i];
1141 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1142 for (unsigned i = 0; i != NumOps; ++i) {
1143 OpsCode += AllOps[i];
1147 emitCode(OpsCode + " };");
1148 Code += ", Ops" + utostr(OpsNo) + ", ";
1149 if (NodeHasOptInFlag) {
1150 Code += "HasInFlag ? ";
1151 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1153 Code += utostr(NumOps);
1160 bool NeedReplace = false;
1162 NodeOps.push_back("Tmp" + utostr(ResNo));
1165 if (NodeHasOutFlag) {
1166 if (!InFlagDecled) {
1167 After.push_back("SDOperand InFlag(ResNode, " +
1168 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1170 InFlagDecled = true;
1172 After.push_back("InFlag = SDOperand(ResNode, " +
1173 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1177 if (FoldedChains.size() > 0) {
1179 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1180 After.push_back("ReplaceUses(SDOperand(" +
1181 FoldedChains[j].first + ".Val, " +
1182 utostr(FoldedChains[j].second) +
1183 "), SDOperand(ResNode, " +
1184 utostr(NumResults+NumDstRegs) + "));");
1188 if (NodeHasOutFlag) {
1189 if (FoldedFlag.first != "") {
1190 After.push_back("ReplaceUses(SDOperand(" + FoldedFlag.first +
1192 utostr(FoldedFlag.second) + "), InFlag);");
1194 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1195 After.push_back("ReplaceUses(SDOperand(N.Val, " +
1196 utostr(NumPatResults + (unsigned)InputHasChain)
1202 if (NeedReplace && InputHasChain) {
1203 After.push_back("ReplaceUses(SDOperand(N.Val, " +
1204 utostr(NumPatResults) + "), SDOperand(" + ChainName
1205 + ".Val, " + ChainName + ".ResNo" + "));");
1206 ChainAssignmentNeeded |= NodeHasChain;
1209 // User does not expect the instruction would produce a chain!
1210 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1212 } else if (InputHasChain && !NodeHasChain) {
1213 // One of the inner node produces a chain.
1215 After.push_back("ReplaceUses(SDOperand(N.Val, " +
1216 utostr(NumPatResults+1) +
1217 "), SDOperand(ResNode, N.ResNo-1));");
1218 After.push_back("ReplaceUses(SDOperand(N.Val, " +
1219 utostr(NumPatResults) + "), " + ChainName + ");");
1224 if (ChainAssignmentNeeded) {
1225 // Remember which op produces the chain.
1226 std::string ChainAssign;
1228 ChainAssign = ChainName + " = SDOperand(" + NodeName +
1229 ".Val, " + utostr(NumResults+NumDstRegs) + ");";
1231 ChainAssign = ChainName + " = SDOperand(" + NodeName +
1232 ", " + utostr(NumResults+NumDstRegs) + ");";
1234 After.push_front(ChainAssign);
1237 // Use getTargetNode or SelectNodeTo? The safe choice is getTargetNode,
1238 // but SelectNodeTo can be faster.
1240 // SelectNodeTo is not safe in a non-root context, or if there is any
1241 // replacement of results needed.
1243 // SelectNodeTo is not profitable if it would require a dynamically
1244 // allocated operand list in a situation where getTargetNode would be
1245 // able to reuse a co-allocated operand list (as in a unary, binary or
1246 // ternary SDNode, for example).
1248 if (!isRoot || NeedReplace ||
1249 (!IsVariadic && AllOps.size() < 4 &&
1250 Pattern->getNumChildren() + InputHasChain + NodeHasInFlag <
1252 Code = "CurDAG->getTargetNode(" + Code;
1254 Code = "CurDAG->SelectNodeTo(N.Val, " + Code;
1258 CodePrefix = "return ";
1260 After.push_back("return ResNode;");
1263 emitCode(CodePrefix + Code + ");");
1264 for (unsigned i = 0, e = After.size(); i != e; ++i)
1268 } else if (Op->isSubClassOf("SDNodeXForm")) {
1269 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1270 // PatLeaf node - the operand may or may not be a leaf node. But it should
1272 std::vector<std::string> Ops =
1273 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1274 ResNodeDecled, true);
1275 unsigned ResNo = TmpNo++;
1276 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1277 + "(" + Ops.back() + ".Val);");
1278 NodeOps.push_back("Tmp" + utostr(ResNo));
1280 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1285 throw std::string("Unknown node in result pattern!");
1289 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1290 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1291 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1292 /// for, this returns true otherwise false if Pat has all types.
1293 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1294 const std::string &Prefix, bool isRoot = false) {
1296 if (Pat->getExtTypes() != Other->getExtTypes()) {
1297 // Move a type over from 'other' to 'pat'.
1298 Pat->setTypes(Other->getExtTypes());
1299 // The top level node type is checked outside of the select function.
1301 emitCheck(Prefix + ".Val->getValueType(0) == " +
1302 getName(Pat->getTypeNum(0)));
1307 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1308 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1309 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1310 Prefix + utostr(OpNo)))
1316 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1318 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1319 bool &ChainEmitted, bool &InFlagDecled,
1320 bool &ResNodeDecled, bool isRoot = false) {
1321 const CodeGenTarget &T = CGP.getTargetInfo();
1323 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1324 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1325 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1326 TreePatternNode *Child = N->getChild(i);
1327 if (!Child->isLeaf()) {
1328 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1329 InFlagDecled, ResNodeDecled);
1331 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1332 if (!Child->getName().empty()) {
1333 std::string Name = RootName + utostr(OpNo);
1334 if (Duplicates.find(Name) != Duplicates.end())
1335 // A duplicate! Do not emit a copy for this node.
1339 Record *RR = DI->getDef();
1340 if (RR->isSubClassOf("Register")) {
1341 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1342 if (RVT == MVT::Flag) {
1343 if (!InFlagDecled) {
1344 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1345 InFlagDecled = true;
1347 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1348 emitCode("AddToISelQueue(InFlag);");
1350 if (!ChainEmitted) {
1351 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1352 ChainName = "Chain";
1353 ChainEmitted = true;
1355 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1356 if (!InFlagDecled) {
1357 emitCode("SDOperand InFlag(0, 0);");
1358 InFlagDecled = true;
1360 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1361 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1362 ", " + getQualifiedName(RR) +
1363 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1364 ResNodeDecled = true;
1365 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1366 emitCode("InFlag = SDOperand(ResNode, 1);");
1374 if (!InFlagDecled) {
1375 emitCode("SDOperand InFlag = " + RootName +
1376 ".getOperand(" + utostr(OpNo) + ");");
1377 InFlagDecled = true;
1379 emitCode("InFlag = " + RootName +
1380 ".getOperand(" + utostr(OpNo) + ");");
1381 emitCode("AddToISelQueue(InFlag);");
1386 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1387 /// stream to match the pattern, and generate the code for the match if it
1388 /// succeeds. Returns true if the pattern is not guaranteed to match.
1389 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1390 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1391 std::set<std::string> &GeneratedDecl,
1392 std::vector<std::string> &TargetOpcodes,
1393 std::vector<std::string> &TargetVTs,
1394 bool &OutputIsVariadic,
1395 unsigned &NumInputRootOps) {
1396 OutputIsVariadic = false;
1397 NumInputRootOps = 0;
1399 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1400 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1401 GeneratedCode, GeneratedDecl,
1402 TargetOpcodes, TargetVTs,
1403 OutputIsVariadic, NumInputRootOps);
1405 // Emit the matcher, capturing named arguments in VariableMap.
1406 bool FoundChain = false;
1407 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1409 // TP - Get *SOME* tree pattern, we don't care which.
1410 TreePattern &TP = *CGP.pf_begin()->second;
1412 // At this point, we know that we structurally match the pattern, but the
1413 // types of the nodes may not match. Figure out the fewest number of type
1414 // comparisons we need to emit. For example, if there is only one integer
1415 // type supported by a target, there should be no type comparisons at all for
1416 // integer patterns!
1418 // To figure out the fewest number of type checks needed, clone the pattern,
1419 // remove the types, then perform type inference on the pattern as a whole.
1420 // If there are unresolved types, emit an explicit check for those types,
1421 // apply the type to the tree, then rerun type inference. Iterate until all
1422 // types are resolved.
1424 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1425 RemoveAllTypes(Pat);
1428 // Resolve/propagate as many types as possible.
1430 bool MadeChange = true;
1432 MadeChange = Pat->ApplyTypeConstraints(TP,
1433 true/*Ignore reg constraints*/);
1435 assert(0 && "Error: could not find consistent types for something we"
1436 " already decided was ok!");
1440 // Insert a check for an unresolved type and add it to the tree. If we find
1441 // an unresolved type to add a check for, this returns true and we iterate,
1442 // otherwise we are done.
1443 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1445 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1446 false, false, false, true);
1450 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1451 /// a line causes any of them to be empty, remove them and return true when
1453 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1454 std::vector<std::pair<unsigned, std::string> > > >
1456 bool ErasedPatterns = false;
1457 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1458 Patterns[i].second.pop_back();
1459 if (Patterns[i].second.empty()) {
1460 Patterns.erase(Patterns.begin()+i);
1462 ErasedPatterns = true;
1465 return ErasedPatterns;
1468 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1469 /// code together between the patterns.
1470 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1471 std::vector<std::pair<unsigned, std::string> > > >
1472 &Patterns, unsigned Indent,
1474 typedef std::pair<unsigned, std::string> CodeLine;
1475 typedef std::vector<CodeLine> CodeList;
1476 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1478 if (Patterns.empty()) return;
1480 // Figure out how many patterns share the next code line. Explicitly copy
1481 // FirstCodeLine so that we don't invalidate a reference when changing
1483 const CodeLine FirstCodeLine = Patterns.back().second.back();
1484 unsigned LastMatch = Patterns.size()-1;
1485 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1488 // If not all patterns share this line, split the list into two pieces. The
1489 // first chunk will use this line, the second chunk won't.
1490 if (LastMatch != 0) {
1491 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1492 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1494 // FIXME: Emit braces?
1495 if (Shared.size() == 1) {
1496 const PatternToMatch &Pattern = *Shared.back().first;
1497 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1498 Pattern.getSrcPattern()->print(OS);
1499 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1500 Pattern.getDstPattern()->print(OS);
1502 unsigned AddedComplexity = Pattern.getAddedComplexity();
1503 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1504 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1506 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1508 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1510 if (FirstCodeLine.first != 1) {
1511 OS << std::string(Indent, ' ') << "{\n";
1514 EmitPatterns(Shared, Indent, OS);
1515 if (FirstCodeLine.first != 1) {
1517 OS << std::string(Indent, ' ') << "}\n";
1520 if (Other.size() == 1) {
1521 const PatternToMatch &Pattern = *Other.back().first;
1522 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1523 Pattern.getSrcPattern()->print(OS);
1524 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1525 Pattern.getDstPattern()->print(OS);
1527 unsigned AddedComplexity = Pattern.getAddedComplexity();
1528 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1529 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1531 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1533 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1535 EmitPatterns(Other, Indent, OS);
1539 // Remove this code from all of the patterns that share it.
1540 bool ErasedPatterns = EraseCodeLine(Patterns);
1542 bool isPredicate = FirstCodeLine.first == 1;
1544 // Otherwise, every pattern in the list has this line. Emit it.
1547 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1549 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1551 // If the next code line is another predicate, and if all of the pattern
1552 // in this group share the same next line, emit it inline now. Do this
1553 // until we run out of common predicates.
1554 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1555 // Check that all of fhe patterns in Patterns end with the same predicate.
1556 bool AllEndWithSamePredicate = true;
1557 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1558 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1559 AllEndWithSamePredicate = false;
1562 // If all of the predicates aren't the same, we can't share them.
1563 if (!AllEndWithSamePredicate) break;
1565 // Otherwise we can. Emit it shared now.
1566 OS << " &&\n" << std::string(Indent+4, ' ')
1567 << Patterns.back().second.back().second;
1568 ErasedPatterns = EraseCodeLine(Patterns);
1575 EmitPatterns(Patterns, Indent, OS);
1578 OS << std::string(Indent-2, ' ') << "}\n";
1581 static std::string getLegalCName(std::string OpName) {
1582 std::string::size_type pos = OpName.find("::");
1583 if (pos != std::string::npos)
1584 OpName.replace(pos, 2, "_");
1588 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1589 const CodeGenTarget &Target = CGP.getTargetInfo();
1591 // Get the namespace to insert instructions into. Make sure not to pick up
1592 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1593 // instruction or something.
1595 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1596 e = Target.inst_end(); i != e; ++i) {
1597 InstNS = i->second.Namespace;
1598 if (InstNS != "TargetInstrInfo")
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 // We want to emit all of the matching code now. However, we want to emit
1654 // the matches in order of minimal cost. Sort the patterns so the least
1655 // cost one is at the start.
1656 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1657 PatternSortingPredicate(CGP));
1659 // Split them into groups by type.
1660 std::map<MVT::SimpleValueType,
1661 std::vector<const PatternToMatch*> > PatternsByType;
1662 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1663 const PatternToMatch *Pat = PatternsOfOp[i];
1664 TreePatternNode *SrcPat = Pat->getSrcPattern();
1665 MVT::SimpleValueType VT = SrcPat->getTypeNum(0);
1666 std::map<MVT::SimpleValueType,
1667 std::vector<const PatternToMatch*> >::iterator TI =
1668 PatternsByType.find(VT);
1669 if (TI != PatternsByType.end())
1670 TI->second.push_back(Pat);
1672 std::vector<const PatternToMatch*> PVec;
1673 PVec.push_back(Pat);
1674 PatternsByType.insert(std::make_pair(VT, PVec));
1678 for (std::map<MVT::SimpleValueType,
1679 std::vector<const PatternToMatch*> >::iterator
1680 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1682 MVT::SimpleValueType OpVT = II->first;
1683 std::vector<const PatternToMatch*> &Patterns = II->second;
1684 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1685 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1687 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1688 std::vector<std::vector<std::string> > PatternOpcodes;
1689 std::vector<std::vector<std::string> > PatternVTs;
1690 std::vector<std::set<std::string> > PatternDecls;
1691 std::vector<bool> OutputIsVariadicFlags;
1692 std::vector<unsigned> NumInputRootOpsCounts;
1693 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1694 CodeList GeneratedCode;
1695 std::set<std::string> GeneratedDecl;
1696 std::vector<std::string> TargetOpcodes;
1697 std::vector<std::string> TargetVTs;
1698 bool OutputIsVariadic;
1699 unsigned NumInputRootOps;
1700 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1701 TargetOpcodes, TargetVTs,
1702 OutputIsVariadic, NumInputRootOps);
1703 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1704 PatternDecls.push_back(GeneratedDecl);
1705 PatternOpcodes.push_back(TargetOpcodes);
1706 PatternVTs.push_back(TargetVTs);
1707 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1708 NumInputRootOpsCounts.push_back(NumInputRootOps);
1711 // Scan the code to see if all of the patterns are reachable and if it is
1712 // possible that the last one might not match.
1713 bool mightNotMatch = true;
1714 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1715 CodeList &GeneratedCode = CodeForPatterns[i].second;
1716 mightNotMatch = false;
1718 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1719 if (GeneratedCode[j].first == 1) { // predicate.
1720 mightNotMatch = true;
1725 // If this pattern definitely matches, and if it isn't the last one, the
1726 // patterns after it CANNOT ever match. Error out.
1727 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1728 cerr << "Pattern '";
1729 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1730 cerr << "' is impossible to select!\n";
1735 // Factor target node emission code (emitted by EmitResultCode) into
1736 // separate functions. Uniquing and share them among all instruction
1737 // selection routines.
1738 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1739 CodeList &GeneratedCode = CodeForPatterns[i].second;
1740 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1741 std::vector<std::string> &TargetVTs = PatternVTs[i];
1742 std::set<std::string> Decls = PatternDecls[i];
1743 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1744 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1745 std::vector<std::string> AddedInits;
1746 int CodeSize = (int)GeneratedCode.size();
1748 for (int j = CodeSize-1; j >= 0; --j) {
1749 if (LastPred == -1 && GeneratedCode[j].first == 1)
1751 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1752 AddedInits.push_back(GeneratedCode[j].second);
1755 std::string CalleeCode = "(const SDOperand &N";
1756 std::string CallerCode = "(N";
1757 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1758 CalleeCode += ", unsigned Opc" + utostr(j);
1759 CallerCode += ", " + TargetOpcodes[j];
1761 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1762 CalleeCode += ", MVT VT" + utostr(j);
1763 CallerCode += ", " + TargetVTs[j];
1765 for (std::set<std::string>::iterator
1766 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1767 std::string Name = *I;
1768 CalleeCode += ", SDOperand &" + Name;
1769 CallerCode += ", " + Name;
1772 if (OutputIsVariadic) {
1773 CalleeCode += ", unsigned NumInputRootOps";
1774 CallerCode += ", " + utostr(NumInputRootOps);
1779 // Prevent emission routines from being inlined to reduce selection
1780 // routines stack frame sizes.
1781 CalleeCode += "DISABLE_INLINE ";
1782 CalleeCode += "{\n";
1784 for (std::vector<std::string>::const_reverse_iterator
1785 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1786 CalleeCode += " " + *I + "\n";
1788 for (int j = LastPred+1; j < CodeSize; ++j)
1789 CalleeCode += " " + GeneratedCode[j].second + "\n";
1790 for (int j = LastPred+1; j < CodeSize; ++j)
1791 GeneratedCode.pop_back();
1792 CalleeCode += "}\n";
1794 // Uniquing the emission routines.
1795 unsigned EmitFuncNum;
1796 std::map<std::string, unsigned>::iterator EFI =
1797 EmitFunctions.find(CalleeCode);
1798 if (EFI != EmitFunctions.end()) {
1799 EmitFuncNum = EFI->second;
1801 EmitFuncNum = EmitFunctions.size();
1802 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1803 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1806 // Replace the emission code within selection routines with calls to the
1807 // emission functions.
1808 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1809 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1813 std::string OpVTStr;
1814 if (OpVT == MVT::iPTR) {
1816 } else if (OpVT == MVT::isVoid) {
1817 // Nodes with a void result actually have a first result type of either
1818 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1819 // void to this case, we handle it specially here.
1821 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1823 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1824 OpcodeVTMap.find(OpName);
1825 if (OpVTI == OpcodeVTMap.end()) {
1826 std::vector<std::string> VTSet;
1827 VTSet.push_back(OpVTStr);
1828 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1830 OpVTI->second.push_back(OpVTStr);
1832 OS << "SDNode *Select_" << getLegalCName(OpName)
1833 << OpVTStr << "(const SDOperand &N) {\n";
1835 // Loop through and reverse all of the CodeList vectors, as we will be
1836 // accessing them from their logical front, but accessing the end of a
1837 // vector is more efficient.
1838 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1839 CodeList &GeneratedCode = CodeForPatterns[i].second;
1840 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1843 // Next, reverse the list of patterns itself for the same reason.
1844 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1846 // Emit all of the patterns now, grouped together to share code.
1847 EmitPatterns(CodeForPatterns, 2, OS);
1849 // If the last pattern has predicates (which could fail) emit code to
1850 // catch the case where nothing handles a pattern.
1851 if (mightNotMatch) {
1852 OS << " cerr << \"Cannot yet select: \";\n";
1853 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1854 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1855 OpName != "ISD::INTRINSIC_VOID") {
1856 OS << " N.Val->dump(CurDAG);\n";
1858 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1859 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1860 << " cerr << \"intrinsic %\"<< "
1861 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1863 OS << " cerr << '\\n';\n"
1865 << " return NULL;\n";
1871 // Emit boilerplate.
1872 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1873 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1874 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1876 << " // Ensure that the asm operands are themselves selected.\n"
1877 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1878 << " AddToISelQueue(Ops[j]);\n\n"
1880 << " std::vector<MVT> VTs;\n"
1881 << " VTs.push_back(MVT::Other);\n"
1882 << " VTs.push_back(MVT::Flag);\n"
1883 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1885 << " return New.Val;\n"
1888 OS << "SDNode *Select_UNDEF(const SDOperand &N) {\n"
1889 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::IMPLICIT_DEF,\n"
1890 << " N.getValueType());\n"
1893 OS << "SDNode *Select_DBG_LABEL(const SDOperand &N) {\n"
1894 << " SDOperand Chain = N.getOperand(0);\n"
1895 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1896 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1897 << " AddToISelQueue(Chain);\n"
1898 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DBG_LABEL,\n"
1899 << " MVT::Other, Tmp, Chain);\n"
1902 OS << "SDNode *Select_EH_LABEL(const SDOperand &N) {\n"
1903 << " SDOperand Chain = N.getOperand(0);\n"
1904 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1905 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1906 << " AddToISelQueue(Chain);\n"
1907 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EH_LABEL,\n"
1908 << " MVT::Other, Tmp, Chain);\n"
1911 OS << "SDNode *Select_DECLARE(const SDOperand &N) {\n"
1912 << " SDOperand Chain = N.getOperand(0);\n"
1913 << " SDOperand N1 = N.getOperand(1);\n"
1914 << " SDOperand N2 = N.getOperand(2);\n"
1915 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1916 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1917 << " N.Val->dump(CurDAG);\n"
1920 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1921 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1922 << " SDOperand Tmp1 = "
1923 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1924 << " SDOperand Tmp2 = "
1925 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1926 << " AddToISelQueue(Chain);\n"
1927 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DECLARE,\n"
1928 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
1931 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1932 << " SDOperand N0 = N.getOperand(0);\n"
1933 << " SDOperand N1 = N.getOperand(1);\n"
1934 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1935 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1936 << " AddToISelQueue(N0);\n"
1937 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EXTRACT_SUBREG,\n"
1938 << " N.getValueType(), N0, Tmp);\n"
1941 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1942 << " SDOperand N0 = N.getOperand(0);\n"
1943 << " SDOperand N1 = N.getOperand(1);\n"
1944 << " SDOperand N2 = N.getOperand(2);\n"
1945 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1946 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1947 << " AddToISelQueue(N1);\n"
1948 << " AddToISelQueue(N0);\n"
1949 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::INSERT_SUBREG,\n"
1950 << " N.getValueType(), N0, N1, Tmp);\n"
1953 OS << "// The main instruction selector code.\n"
1954 << "SDNode *SelectCode(SDOperand N) {\n"
1955 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1956 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1957 << "INSTRUCTION_LIST_END)) {\n"
1958 << " return NULL; // Already selected.\n"
1960 << " MVT::SimpleValueType NVT = N.Val->getValueType(0).getSimpleVT();\n"
1961 << " switch (N.getOpcode()) {\n"
1962 << " default: break;\n"
1963 << " case ISD::EntryToken: // These leaves remain the same.\n"
1964 << " case ISD::BasicBlock:\n"
1965 << " case ISD::Register:\n"
1966 << " case ISD::HANDLENODE:\n"
1967 << " case ISD::TargetConstant:\n"
1968 << " case ISD::TargetConstantFP:\n"
1969 << " case ISD::TargetConstantPool:\n"
1970 << " case ISD::TargetFrameIndex:\n"
1971 << " case ISD::TargetExternalSymbol:\n"
1972 << " case ISD::TargetJumpTable:\n"
1973 << " case ISD::TargetGlobalTLSAddress:\n"
1974 << " case ISD::TargetGlobalAddress: {\n"
1975 << " return NULL;\n"
1977 << " case ISD::AssertSext:\n"
1978 << " case ISD::AssertZext: {\n"
1979 << " AddToISelQueue(N.getOperand(0));\n"
1980 << " ReplaceUses(N, N.getOperand(0));\n"
1981 << " return NULL;\n"
1983 << " case ISD::TokenFactor:\n"
1984 << " case ISD::CopyFromReg:\n"
1985 << " case ISD::CopyToReg: {\n"
1986 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1987 << " AddToISelQueue(N.getOperand(i));\n"
1988 << " return NULL;\n"
1990 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1991 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1992 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1993 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
1994 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1995 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
1996 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1999 // Loop over all of the case statements, emiting a call to each method we
2001 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
2002 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
2003 PBOI != E; ++PBOI) {
2004 const std::string &OpName = PBOI->first;
2005 // Potentially multiple versions of select for this opcode. One for each
2006 // ValueType of the node (or its first true operand if it doesn't produce a
2008 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2009 OpcodeVTMap.find(OpName);
2010 std::vector<std::string> &OpVTs = OpVTI->second;
2011 OS << " case " << OpName << ": {\n";
2012 // Keep track of whether we see a pattern that has an iPtr result.
2013 bool HasPtrPattern = false;
2014 bool HasDefaultPattern = false;
2016 OS << " switch (NVT) {\n";
2017 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2018 std::string &VTStr = OpVTs[i];
2019 if (VTStr.empty()) {
2020 HasDefaultPattern = true;
2024 // If this is a match on iPTR: don't emit it directly, we need special
2026 if (VTStr == "_iPTR") {
2027 HasPtrPattern = true;
2030 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2031 << " return Select_" << getLegalCName(OpName)
2032 << VTStr << "(N);\n";
2034 OS << " default:\n";
2036 // If there is an iPTR result version of this pattern, emit it here.
2037 if (HasPtrPattern) {
2038 OS << " if (TLI.getPointerTy() == NVT)\n";
2039 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2041 if (HasDefaultPattern) {
2042 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2050 OS << " } // end of big switch.\n\n"
2051 << " cerr << \"Cannot yet select: \";\n"
2052 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2053 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2054 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2055 << " N.Val->dump(CurDAG);\n"
2057 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2058 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
2059 << " cerr << \"intrinsic %\"<< "
2060 "Intrinsic::getName((Intrinsic::ID)iid);\n"
2062 << " cerr << '\\n';\n"
2064 << " return NULL;\n"
2068 void DAGISelEmitter::run(std::ostream &OS) {
2069 EmitSourceFileHeader("DAG Instruction Selector for the " +
2070 CGP.getTargetInfo().getName() + " target", OS);
2072 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2073 << "// *** instruction selector class. These functions are really "
2076 OS << "// Include standard, target-independent definitions and methods used\n"
2077 << "// by the instruction selector.\n";
2078 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
2080 EmitNodeTransforms(OS);
2081 EmitPredicateFunctions(OS);
2083 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2084 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2086 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2087 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2091 // At this point, we have full information about the 'Patterns' we need to
2092 // parse, both implicitly from instructions as well as from explicit pattern
2093 // definitions. Emit the resultant instruction selector.
2094 EmitInstructionSelector(OS);