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 SDValue 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 SDValue 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("SDValue " + 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("SDValue " + RootName + "0" + " = " +
582 RootName + ".getOperand(" + utostr(0) + ");");
583 emitInit("SDValue " + 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("SDValue " + 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("SDValue CPTmp" + utostr(i) + ";");
616 if (CP->hasProperty(SDNPHasChain)) {
617 emitDecl("CPInChain");
618 emitDecl("Chain" + ChainSuffix);
619 emitCode("SDValue CPInChain;");
620 emitCode("SDValue 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("SDValue 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("SDValue CPInChain;");
698 emitCode("SDValue " + 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("SDValue " + 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("SDValue " + 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("SDValue " + 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("SDValue " + 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("SDValue 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("SDValue 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("SDValue 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<SDValue, 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<SDValue, 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("SDValue 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 = "SDValue " + 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("SDValue 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 = "SDValue 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 std::vector<std::string> ReplaceFroms;
1161 std::vector<std::string> ReplaceTos;
1163 NodeOps.push_back("Tmp" + utostr(ResNo));
1166 if (NodeHasOutFlag) {
1167 if (!InFlagDecled) {
1168 After.push_back("SDValue InFlag(ResNode, " +
1169 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1171 InFlagDecled = true;
1173 After.push_back("InFlag = SDValue(ResNode, " +
1174 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1178 if (FoldedChains.size() > 0) {
1180 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1181 ReplaceFroms.push_back("SDValue(" +
1182 FoldedChains[j].first + ".Val, " +
1183 utostr(FoldedChains[j].second) +
1185 ReplaceTos.push_back("SDValue(ResNode, " +
1186 utostr(NumResults+NumDstRegs) + ")");
1190 if (NodeHasOutFlag) {
1191 if (FoldedFlag.first != "") {
1192 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".Val, " +
1193 utostr(FoldedFlag.second) + ")");
1194 ReplaceTos.push_back("InFlag");
1196 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1197 ReplaceFroms.push_back("SDValue(N.Val, " +
1198 utostr(NumPatResults + (unsigned)InputHasChain)
1200 ReplaceTos.push_back("InFlag");
1204 if (!ReplaceFroms.empty() && InputHasChain) {
1205 ReplaceFroms.push_back("SDValue(N.Val, " +
1206 utostr(NumPatResults) + ")");
1207 ReplaceTos.push_back("SDValue(" + ChainName + ".Val, " +
1208 ChainName + ".ResNo" + ")");
1209 ChainAssignmentNeeded |= NodeHasChain;
1212 // User does not expect the instruction would produce a chain!
1213 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1215 } else if (InputHasChain && !NodeHasChain) {
1216 // One of the inner node produces a chain.
1217 if (NodeHasOutFlag) {
1218 ReplaceFroms.push_back("SDValue(N.Val, " +
1219 utostr(NumPatResults+1) +
1221 ReplaceTos.push_back("SDValue(ResNode, N.ResNo-1)");
1223 ReplaceFroms.push_back("SDValue(N.Val, " +
1224 utostr(NumPatResults) + ")");
1225 ReplaceTos.push_back(ChainName);
1229 if (ChainAssignmentNeeded) {
1230 // Remember which op produces the chain.
1231 std::string ChainAssign;
1233 ChainAssign = ChainName + " = SDValue(" + NodeName +
1234 ".Val, " + utostr(NumResults+NumDstRegs) + ");";
1236 ChainAssign = ChainName + " = SDValue(" + NodeName +
1237 ", " + utostr(NumResults+NumDstRegs) + ");";
1239 After.push_front(ChainAssign);
1242 if (ReplaceFroms.size() == 1) {
1243 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1244 ReplaceTos[0] + ");");
1245 } else if (!ReplaceFroms.empty()) {
1246 After.push_back("const SDValue Froms[] = {");
1247 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1248 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1249 After.push_back("};");
1250 After.push_back("const SDValue Tos[] = {");
1251 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1252 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1253 After.push_back("};");
1254 After.push_back("ReplaceUses(Froms, Tos, " +
1255 itostr(ReplaceFroms.size()) + ");");
1258 // We prefer to use SelectNodeTo since it avoids allocation when
1259 // possible and it avoids CSE map recalculation for the node's
1260 // users, however it's tricky to use in a non-root context.
1262 // We also don't use if the pattern replacement is being used to
1263 // jettison a chain result, since morphing the node in place
1264 // would leave users of the chain dangling.
1266 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1267 Code = "CurDAG->getTargetNode(" + Code;
1269 Code = "CurDAG->SelectNodeTo(N.Val, " + Code;
1273 CodePrefix = "return ";
1275 After.push_back("return ResNode;");
1278 emitCode(CodePrefix + Code + ");");
1279 for (unsigned i = 0, e = After.size(); i != e; ++i)
1283 } else if (Op->isSubClassOf("SDNodeXForm")) {
1284 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1285 // PatLeaf node - the operand may or may not be a leaf node. But it should
1287 std::vector<std::string> Ops =
1288 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1289 ResNodeDecled, true);
1290 unsigned ResNo = TmpNo++;
1291 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1292 + "(" + Ops.back() + ".Val);");
1293 NodeOps.push_back("Tmp" + utostr(ResNo));
1295 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1300 throw std::string("Unknown node in result pattern!");
1304 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1305 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1306 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1307 /// for, this returns true otherwise false if Pat has all types.
1308 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1309 const std::string &Prefix, bool isRoot = false) {
1311 if (Pat->getExtTypes() != Other->getExtTypes()) {
1312 // Move a type over from 'other' to 'pat'.
1313 Pat->setTypes(Other->getExtTypes());
1314 // The top level node type is checked outside of the select function.
1316 emitCheck(Prefix + ".Val->getValueType(0) == " +
1317 getName(Pat->getTypeNum(0)));
1322 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1323 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1324 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1325 Prefix + utostr(OpNo)))
1331 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1333 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1334 bool &ChainEmitted, bool &InFlagDecled,
1335 bool &ResNodeDecled, bool isRoot = false) {
1336 const CodeGenTarget &T = CGP.getTargetInfo();
1338 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1339 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1340 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1341 TreePatternNode *Child = N->getChild(i);
1342 if (!Child->isLeaf()) {
1343 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1344 InFlagDecled, ResNodeDecled);
1346 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1347 if (!Child->getName().empty()) {
1348 std::string Name = RootName + utostr(OpNo);
1349 if (Duplicates.find(Name) != Duplicates.end())
1350 // A duplicate! Do not emit a copy for this node.
1354 Record *RR = DI->getDef();
1355 if (RR->isSubClassOf("Register")) {
1356 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1357 if (RVT == MVT::Flag) {
1358 if (!InFlagDecled) {
1359 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1360 InFlagDecled = true;
1362 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1363 emitCode("AddToISelQueue(InFlag);");
1365 if (!ChainEmitted) {
1366 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1367 ChainName = "Chain";
1368 ChainEmitted = true;
1370 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1371 if (!InFlagDecled) {
1372 emitCode("SDValue InFlag(0, 0);");
1373 InFlagDecled = true;
1375 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1376 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1377 ", " + getQualifiedName(RR) +
1378 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1379 ResNodeDecled = true;
1380 emitCode(ChainName + " = SDValue(ResNode, 0);");
1381 emitCode("InFlag = SDValue(ResNode, 1);");
1389 if (!InFlagDecled) {
1390 emitCode("SDValue InFlag = " + RootName +
1391 ".getOperand(" + utostr(OpNo) + ");");
1392 InFlagDecled = true;
1394 emitCode("InFlag = " + RootName +
1395 ".getOperand(" + utostr(OpNo) + ");");
1396 emitCode("AddToISelQueue(InFlag);");
1401 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1402 /// stream to match the pattern, and generate the code for the match if it
1403 /// succeeds. Returns true if the pattern is not guaranteed to match.
1404 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1405 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1406 std::set<std::string> &GeneratedDecl,
1407 std::vector<std::string> &TargetOpcodes,
1408 std::vector<std::string> &TargetVTs,
1409 bool &OutputIsVariadic,
1410 unsigned &NumInputRootOps) {
1411 OutputIsVariadic = false;
1412 NumInputRootOps = 0;
1414 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
1415 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1416 GeneratedCode, GeneratedDecl,
1417 TargetOpcodes, TargetVTs,
1418 OutputIsVariadic, NumInputRootOps);
1420 // Emit the matcher, capturing named arguments in VariableMap.
1421 bool FoundChain = false;
1422 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1424 // TP - Get *SOME* tree pattern, we don't care which.
1425 TreePattern &TP = *CGP.pf_begin()->second;
1427 // At this point, we know that we structurally match the pattern, but the
1428 // types of the nodes may not match. Figure out the fewest number of type
1429 // comparisons we need to emit. For example, if there is only one integer
1430 // type supported by a target, there should be no type comparisons at all for
1431 // integer patterns!
1433 // To figure out the fewest number of type checks needed, clone the pattern,
1434 // remove the types, then perform type inference on the pattern as a whole.
1435 // If there are unresolved types, emit an explicit check for those types,
1436 // apply the type to the tree, then rerun type inference. Iterate until all
1437 // types are resolved.
1439 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1440 RemoveAllTypes(Pat);
1443 // Resolve/propagate as many types as possible.
1445 bool MadeChange = true;
1447 MadeChange = Pat->ApplyTypeConstraints(TP,
1448 true/*Ignore reg constraints*/);
1450 assert(0 && "Error: could not find consistent types for something we"
1451 " already decided was ok!");
1455 // Insert a check for an unresolved type and add it to the tree. If we find
1456 // an unresolved type to add a check for, this returns true and we iterate,
1457 // otherwise we are done.
1458 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1460 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1461 false, false, false, true);
1465 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1466 /// a line causes any of them to be empty, remove them and return true when
1468 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1469 std::vector<std::pair<unsigned, std::string> > > >
1471 bool ErasedPatterns = false;
1472 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1473 Patterns[i].second.pop_back();
1474 if (Patterns[i].second.empty()) {
1475 Patterns.erase(Patterns.begin()+i);
1477 ErasedPatterns = true;
1480 return ErasedPatterns;
1483 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1484 /// code together between the patterns.
1485 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1486 std::vector<std::pair<unsigned, std::string> > > >
1487 &Patterns, unsigned Indent,
1489 typedef std::pair<unsigned, std::string> CodeLine;
1490 typedef std::vector<CodeLine> CodeList;
1491 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1493 if (Patterns.empty()) return;
1495 // Figure out how many patterns share the next code line. Explicitly copy
1496 // FirstCodeLine so that we don't invalidate a reference when changing
1498 const CodeLine FirstCodeLine = Patterns.back().second.back();
1499 unsigned LastMatch = Patterns.size()-1;
1500 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1503 // If not all patterns share this line, split the list into two pieces. The
1504 // first chunk will use this line, the second chunk won't.
1505 if (LastMatch != 0) {
1506 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1507 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1509 // FIXME: Emit braces?
1510 if (Shared.size() == 1) {
1511 const PatternToMatch &Pattern = *Shared.back().first;
1512 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1513 Pattern.getSrcPattern()->print(OS);
1514 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1515 Pattern.getDstPattern()->print(OS);
1517 unsigned AddedComplexity = Pattern.getAddedComplexity();
1518 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1519 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1521 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1523 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1525 if (FirstCodeLine.first != 1) {
1526 OS << std::string(Indent, ' ') << "{\n";
1529 EmitPatterns(Shared, Indent, OS);
1530 if (FirstCodeLine.first != 1) {
1532 OS << std::string(Indent, ' ') << "}\n";
1535 if (Other.size() == 1) {
1536 const PatternToMatch &Pattern = *Other.back().first;
1537 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1538 Pattern.getSrcPattern()->print(OS);
1539 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1540 Pattern.getDstPattern()->print(OS);
1542 unsigned AddedComplexity = Pattern.getAddedComplexity();
1543 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1544 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1546 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1548 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1550 EmitPatterns(Other, Indent, OS);
1554 // Remove this code from all of the patterns that share it.
1555 bool ErasedPatterns = EraseCodeLine(Patterns);
1557 bool isPredicate = FirstCodeLine.first == 1;
1559 // Otherwise, every pattern in the list has this line. Emit it.
1562 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1564 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1566 // If the next code line is another predicate, and if all of the pattern
1567 // in this group share the same next line, emit it inline now. Do this
1568 // until we run out of common predicates.
1569 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1570 // Check that all of fhe patterns in Patterns end with the same predicate.
1571 bool AllEndWithSamePredicate = true;
1572 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1573 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1574 AllEndWithSamePredicate = false;
1577 // If all of the predicates aren't the same, we can't share them.
1578 if (!AllEndWithSamePredicate) break;
1580 // Otherwise we can. Emit it shared now.
1581 OS << " &&\n" << std::string(Indent+4, ' ')
1582 << Patterns.back().second.back().second;
1583 ErasedPatterns = EraseCodeLine(Patterns);
1590 EmitPatterns(Patterns, Indent, OS);
1593 OS << std::string(Indent-2, ' ') << "}\n";
1596 static std::string getLegalCName(std::string OpName) {
1597 std::string::size_type pos = OpName.find("::");
1598 if (pos != std::string::npos)
1599 OpName.replace(pos, 2, "_");
1603 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1604 const CodeGenTarget &Target = CGP.getTargetInfo();
1606 // Get the namespace to insert instructions into. Make sure not to pick up
1607 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1608 // instruction or something.
1610 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1611 e = Target.inst_end(); i != e; ++i) {
1612 InstNS = i->second.Namespace;
1613 if (InstNS != "TargetInstrInfo")
1617 if (!InstNS.empty()) InstNS += "::";
1619 // Group the patterns by their top-level opcodes.
1620 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1621 // All unique target node emission functions.
1622 std::map<std::string, unsigned> EmitFunctions;
1623 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1624 E = CGP.ptm_end(); I != E; ++I) {
1625 const PatternToMatch &Pattern = *I;
1627 TreePatternNode *Node = Pattern.getSrcPattern();
1628 if (!Node->isLeaf()) {
1629 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1630 push_back(&Pattern);
1632 const ComplexPattern *CP;
1633 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1634 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1635 push_back(&Pattern);
1636 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1637 std::vector<Record*> OpNodes = CP->getRootNodes();
1638 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1639 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1640 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1644 cerr << "Unrecognized opcode '";
1646 cerr << "' on tree pattern '";
1647 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1653 // For each opcode, there might be multiple select functions, one per
1654 // ValueType of the node (or its first operand if it doesn't produce a
1655 // non-chain result.
1656 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1658 // Emit one Select_* method for each top-level opcode. We do this instead of
1659 // emitting one giant switch statement to support compilers where this will
1660 // result in the recursive functions taking less stack space.
1661 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1662 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1663 PBOI != E; ++PBOI) {
1664 const std::string &OpName = PBOI->first;
1665 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1666 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1668 // We want to emit all of the matching code now. However, we want to emit
1669 // the matches in order of minimal cost. Sort the patterns so the least
1670 // cost one is at the start.
1671 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1672 PatternSortingPredicate(CGP));
1674 // Split them into groups by type.
1675 std::map<MVT::SimpleValueType,
1676 std::vector<const PatternToMatch*> > PatternsByType;
1677 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1678 const PatternToMatch *Pat = PatternsOfOp[i];
1679 TreePatternNode *SrcPat = Pat->getSrcPattern();
1680 MVT::SimpleValueType VT = SrcPat->getTypeNum(0);
1681 std::map<MVT::SimpleValueType,
1682 std::vector<const PatternToMatch*> >::iterator TI =
1683 PatternsByType.find(VT);
1684 if (TI != PatternsByType.end())
1685 TI->second.push_back(Pat);
1687 std::vector<const PatternToMatch*> PVec;
1688 PVec.push_back(Pat);
1689 PatternsByType.insert(std::make_pair(VT, PVec));
1693 for (std::map<MVT::SimpleValueType,
1694 std::vector<const PatternToMatch*> >::iterator
1695 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1697 MVT::SimpleValueType OpVT = II->first;
1698 std::vector<const PatternToMatch*> &Patterns = II->second;
1699 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1700 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1702 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1703 std::vector<std::vector<std::string> > PatternOpcodes;
1704 std::vector<std::vector<std::string> > PatternVTs;
1705 std::vector<std::set<std::string> > PatternDecls;
1706 std::vector<bool> OutputIsVariadicFlags;
1707 std::vector<unsigned> NumInputRootOpsCounts;
1708 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1709 CodeList GeneratedCode;
1710 std::set<std::string> GeneratedDecl;
1711 std::vector<std::string> TargetOpcodes;
1712 std::vector<std::string> TargetVTs;
1713 bool OutputIsVariadic;
1714 unsigned NumInputRootOps;
1715 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1716 TargetOpcodes, TargetVTs,
1717 OutputIsVariadic, NumInputRootOps);
1718 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1719 PatternDecls.push_back(GeneratedDecl);
1720 PatternOpcodes.push_back(TargetOpcodes);
1721 PatternVTs.push_back(TargetVTs);
1722 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1723 NumInputRootOpsCounts.push_back(NumInputRootOps);
1726 // Scan the code to see if all of the patterns are reachable and if it is
1727 // possible that the last one might not match.
1728 bool mightNotMatch = true;
1729 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1730 CodeList &GeneratedCode = CodeForPatterns[i].second;
1731 mightNotMatch = false;
1733 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1734 if (GeneratedCode[j].first == 1) { // predicate.
1735 mightNotMatch = true;
1740 // If this pattern definitely matches, and if it isn't the last one, the
1741 // patterns after it CANNOT ever match. Error out.
1742 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1743 cerr << "Pattern '";
1744 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1745 cerr << "' is impossible to select!\n";
1750 // Factor target node emission code (emitted by EmitResultCode) into
1751 // separate functions. Uniquing and share them among all instruction
1752 // selection routines.
1753 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1754 CodeList &GeneratedCode = CodeForPatterns[i].second;
1755 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1756 std::vector<std::string> &TargetVTs = PatternVTs[i];
1757 std::set<std::string> Decls = PatternDecls[i];
1758 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1759 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1760 std::vector<std::string> AddedInits;
1761 int CodeSize = (int)GeneratedCode.size();
1763 for (int j = CodeSize-1; j >= 0; --j) {
1764 if (LastPred == -1 && GeneratedCode[j].first == 1)
1766 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1767 AddedInits.push_back(GeneratedCode[j].second);
1770 std::string CalleeCode = "(const SDValue &N";
1771 std::string CallerCode = "(N";
1772 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1773 CalleeCode += ", unsigned Opc" + utostr(j);
1774 CallerCode += ", " + TargetOpcodes[j];
1776 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1777 CalleeCode += ", MVT VT" + utostr(j);
1778 CallerCode += ", " + TargetVTs[j];
1780 for (std::set<std::string>::iterator
1781 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1782 std::string Name = *I;
1783 CalleeCode += ", SDValue &" + Name;
1784 CallerCode += ", " + Name;
1787 if (OutputIsVariadic) {
1788 CalleeCode += ", unsigned NumInputRootOps";
1789 CallerCode += ", " + utostr(NumInputRootOps);
1794 // Prevent emission routines from being inlined to reduce selection
1795 // routines stack frame sizes.
1796 CalleeCode += "DISABLE_INLINE ";
1797 CalleeCode += "{\n";
1799 for (std::vector<std::string>::const_reverse_iterator
1800 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1801 CalleeCode += " " + *I + "\n";
1803 for (int j = LastPred+1; j < CodeSize; ++j)
1804 CalleeCode += " " + GeneratedCode[j].second + "\n";
1805 for (int j = LastPred+1; j < CodeSize; ++j)
1806 GeneratedCode.pop_back();
1807 CalleeCode += "}\n";
1809 // Uniquing the emission routines.
1810 unsigned EmitFuncNum;
1811 std::map<std::string, unsigned>::iterator EFI =
1812 EmitFunctions.find(CalleeCode);
1813 if (EFI != EmitFunctions.end()) {
1814 EmitFuncNum = EFI->second;
1816 EmitFuncNum = EmitFunctions.size();
1817 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1818 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1821 // Replace the emission code within selection routines with calls to the
1822 // emission functions.
1823 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1824 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1828 std::string OpVTStr;
1829 if (OpVT == MVT::iPTR) {
1831 } else if (OpVT == MVT::isVoid) {
1832 // Nodes with a void result actually have a first result type of either
1833 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1834 // void to this case, we handle it specially here.
1836 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1838 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1839 OpcodeVTMap.find(OpName);
1840 if (OpVTI == OpcodeVTMap.end()) {
1841 std::vector<std::string> VTSet;
1842 VTSet.push_back(OpVTStr);
1843 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1845 OpVTI->second.push_back(OpVTStr);
1847 OS << "SDNode *Select_" << getLegalCName(OpName)
1848 << OpVTStr << "(const SDValue &N) {\n";
1850 // Loop through and reverse all of the CodeList vectors, as we will be
1851 // accessing them from their logical front, but accessing the end of a
1852 // vector is more efficient.
1853 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1854 CodeList &GeneratedCode = CodeForPatterns[i].second;
1855 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1858 // Next, reverse the list of patterns itself for the same reason.
1859 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1861 // Emit all of the patterns now, grouped together to share code.
1862 EmitPatterns(CodeForPatterns, 2, OS);
1864 // If the last pattern has predicates (which could fail) emit code to
1865 // catch the case where nothing handles a pattern.
1866 if (mightNotMatch) {
1867 OS << " cerr << \"Cannot yet select: \";\n";
1868 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1869 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1870 OpName != "ISD::INTRINSIC_VOID") {
1871 OS << " N.Val->dump(CurDAG);\n";
1873 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1874 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1875 << " cerr << \"intrinsic %\"<< "
1876 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1878 OS << " cerr << '\\n';\n"
1880 << " return NULL;\n";
1886 // Emit boilerplate.
1887 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1888 << " std::vector<SDValue> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1889 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1891 << " // Ensure that the asm operands are themselves selected.\n"
1892 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1893 << " AddToISelQueue(Ops[j]);\n\n"
1895 << " std::vector<MVT> VTs;\n"
1896 << " VTs.push_back(MVT::Other);\n"
1897 << " VTs.push_back(MVT::Flag);\n"
1898 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1900 << " return New.Val;\n"
1903 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1904 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::IMPLICIT_DEF,\n"
1905 << " N.getValueType());\n"
1908 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1909 << " SDValue Chain = N.getOperand(0);\n"
1910 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1911 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1912 << " AddToISelQueue(Chain);\n"
1913 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DBG_LABEL,\n"
1914 << " MVT::Other, Tmp, Chain);\n"
1917 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1918 << " SDValue Chain = N.getOperand(0);\n"
1919 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1920 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1921 << " AddToISelQueue(Chain);\n"
1922 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EH_LABEL,\n"
1923 << " MVT::Other, Tmp, Chain);\n"
1926 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1927 << " SDValue Chain = N.getOperand(0);\n"
1928 << " SDValue N1 = N.getOperand(1);\n"
1929 << " SDValue N2 = N.getOperand(2);\n"
1930 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
1931 << " cerr << \"Cannot yet select llvm.dbg.declare: \";\n"
1932 << " N.Val->dump(CurDAG);\n"
1935 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1936 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
1937 << " SDValue Tmp1 = "
1938 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
1939 << " SDValue Tmp2 = "
1940 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
1941 << " AddToISelQueue(Chain);\n"
1942 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::DECLARE,\n"
1943 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
1946 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1947 << " SDValue N0 = N.getOperand(0);\n"
1948 << " SDValue N1 = N.getOperand(1);\n"
1949 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1950 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1951 << " AddToISelQueue(N0);\n"
1952 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::EXTRACT_SUBREG,\n"
1953 << " N.getValueType(), N0, Tmp);\n"
1956 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1957 << " SDValue N0 = N.getOperand(0);\n"
1958 << " SDValue N1 = N.getOperand(1);\n"
1959 << " SDValue N2 = N.getOperand(2);\n"
1960 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1961 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1962 << " AddToISelQueue(N1);\n"
1963 << " AddToISelQueue(N0);\n"
1964 << " return CurDAG->SelectNodeTo(N.Val, TargetInstrInfo::INSERT_SUBREG,\n"
1965 << " N.getValueType(), N0, N1, Tmp);\n"
1968 OS << "// The main instruction selector code.\n"
1969 << "SDNode *SelectCode(SDValue N) {\n"
1970 << " if (N.isMachineOpcode()) {\n"
1971 << " return NULL; // Already selected.\n"
1973 << " MVT::SimpleValueType NVT = N.Val->getValueType(0).getSimpleVT();\n"
1974 << " switch (N.getOpcode()) {\n"
1975 << " default: break;\n"
1976 << " case ISD::EntryToken: // These leaves remain the same.\n"
1977 << " case ISD::BasicBlock:\n"
1978 << " case ISD::Register:\n"
1979 << " case ISD::HANDLENODE:\n"
1980 << " case ISD::TargetConstant:\n"
1981 << " case ISD::TargetConstantFP:\n"
1982 << " case ISD::TargetConstantPool:\n"
1983 << " case ISD::TargetFrameIndex:\n"
1984 << " case ISD::TargetExternalSymbol:\n"
1985 << " case ISD::TargetJumpTable:\n"
1986 << " case ISD::TargetGlobalTLSAddress:\n"
1987 << " case ISD::TargetGlobalAddress: {\n"
1988 << " return NULL;\n"
1990 << " case ISD::AssertSext:\n"
1991 << " case ISD::AssertZext: {\n"
1992 << " AddToISelQueue(N.getOperand(0));\n"
1993 << " ReplaceUses(N, N.getOperand(0));\n"
1994 << " return NULL;\n"
1996 << " case ISD::TokenFactor:\n"
1997 << " case ISD::CopyFromReg:\n"
1998 << " case ISD::CopyToReg: {\n"
1999 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
2000 << " AddToISelQueue(N.getOperand(i));\n"
2001 << " return NULL;\n"
2003 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
2004 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
2005 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
2006 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
2007 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
2008 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
2009 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
2012 // Loop over all of the case statements, emiting a call to each method we
2014 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
2015 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
2016 PBOI != E; ++PBOI) {
2017 const std::string &OpName = PBOI->first;
2018 // Potentially multiple versions of select for this opcode. One for each
2019 // ValueType of the node (or its first true operand if it doesn't produce a
2021 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2022 OpcodeVTMap.find(OpName);
2023 std::vector<std::string> &OpVTs = OpVTI->second;
2024 OS << " case " << OpName << ": {\n";
2025 // Keep track of whether we see a pattern that has an iPtr result.
2026 bool HasPtrPattern = false;
2027 bool HasDefaultPattern = false;
2029 OS << " switch (NVT) {\n";
2030 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2031 std::string &VTStr = OpVTs[i];
2032 if (VTStr.empty()) {
2033 HasDefaultPattern = true;
2037 // If this is a match on iPTR: don't emit it directly, we need special
2039 if (VTStr == "_iPTR") {
2040 HasPtrPattern = true;
2043 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2044 << " return Select_" << getLegalCName(OpName)
2045 << VTStr << "(N);\n";
2047 OS << " default:\n";
2049 // If there is an iPTR result version of this pattern, emit it here.
2050 if (HasPtrPattern) {
2051 OS << " if (TLI.getPointerTy() == NVT)\n";
2052 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2054 if (HasDefaultPattern) {
2055 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2063 OS << " } // end of big switch.\n\n"
2064 << " cerr << \"Cannot yet select: \";\n"
2065 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2066 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2067 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2068 << " N.Val->dump(CurDAG);\n"
2070 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2071 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
2072 << " cerr << \"intrinsic %\"<< "
2073 "Intrinsic::getName((Intrinsic::ID)iid);\n"
2075 << " cerr << '\\n';\n"
2077 << " return NULL;\n"
2081 void DAGISelEmitter::run(std::ostream &OS) {
2082 EmitSourceFileHeader("DAG Instruction Selector for the " +
2083 CGP.getTargetInfo().getName() + " target", OS);
2085 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2086 << "// *** instruction selector class. These functions are really "
2089 OS << "// Include standard, target-independent definitions and methods used\n"
2090 << "// by the instruction selector.\n";
2091 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
2093 EmitNodeTransforms(OS);
2094 EmitPredicateFunctions(OS);
2096 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2097 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2099 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2100 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2104 // At this point, we have full information about the 'Patterns' we need to
2105 // parse, both implicitly from instructions as well as from explicit pattern
2106 // definitions. Emit the resultant instruction selector.
2107 EmitInstructionSelector(OS);