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/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Streams.h"
28 GenDebug("gen-debug", cl::desc("Generate debug code"),
32 //===----------------------------------------------------------------------===//
33 // DAGISelEmitter Helper methods
36 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
38 static bool NodeIsComplexPattern(TreePatternNode *N) {
39 return (N->isLeaf() &&
40 dynamic_cast<DefInit*>(N->getLeafValue()) &&
41 static_cast<DefInit*>(N->getLeafValue())->getDef()->
42 isSubClassOf("ComplexPattern"));
45 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
46 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
47 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
48 CodeGenDAGPatterns &CGP) {
50 dynamic_cast<DefInit*>(N->getLeafValue()) &&
51 static_cast<DefInit*>(N->getLeafValue())->getDef()->
52 isSubClassOf("ComplexPattern")) {
53 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
59 /// getPatternSize - Return the 'size' of this pattern. We want to match large
60 /// patterns before small ones. This is used to determine the size of a
62 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
63 assert((EMVT::isExtIntegerInVTs(P->getExtTypes()) ||
64 EMVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
65 P->getExtTypeNum(0) == MVT::isVoid ||
66 P->getExtTypeNum(0) == MVT::Flag ||
67 P->getExtTypeNum(0) == MVT::iPTR ||
68 P->getExtTypeNum(0) == MVT::iPTRAny) &&
69 "Not a valid pattern node to size!");
70 unsigned Size = 3; // The node itself.
71 // If the root node is a ConstantSDNode, increases its size.
72 // e.g. (set R32:$dst, 0).
73 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
76 // FIXME: This is a hack to statically increase the priority of patterns
77 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
78 // Later we can allow complexity / cost for each pattern to be (optionally)
79 // specified. To get best possible pattern match we'll need to dynamically
80 // calculate the complexity of all patterns a dag can potentially map to.
81 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
83 Size += AM->getNumOperands() * 3;
85 // If this node has some predicate function that must match, it adds to the
86 // complexity of this node.
87 if (!P->getPredicateFns().empty())
90 // Count children in the count if they are also nodes.
91 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
92 TreePatternNode *Child = P->getChild(i);
93 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
94 Size += getPatternSize(Child, CGP);
95 else if (Child->isLeaf()) {
96 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
97 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
98 else if (NodeIsComplexPattern(Child))
99 Size += getPatternSize(Child, CGP);
100 else if (!Child->getPredicateFns().empty())
108 /// getResultPatternCost - Compute the number of instructions for this pattern.
109 /// This is a temporary hack. We should really include the instruction
110 /// latencies in this calculation.
111 static unsigned getResultPatternCost(TreePatternNode *P,
112 CodeGenDAGPatterns &CGP) {
113 if (P->isLeaf()) return 0;
116 Record *Op = P->getOperator();
117 if (Op->isSubClassOf("Instruction")) {
119 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
120 if (II.usesCustomDAGSchedInserter)
123 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
124 Cost += getResultPatternCost(P->getChild(i), CGP);
128 /// getResultPatternCodeSize - Compute the code size of instructions for this
130 static unsigned getResultPatternSize(TreePatternNode *P,
131 CodeGenDAGPatterns &CGP) {
132 if (P->isLeaf()) return 0;
135 Record *Op = P->getOperator();
136 if (Op->isSubClassOf("Instruction")) {
137 Cost += Op->getValueAsInt("CodeSize");
139 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
140 Cost += getResultPatternSize(P->getChild(i), CGP);
144 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
145 // In particular, we want to match maximal patterns first and lowest cost within
146 // a particular complexity first.
147 struct PatternSortingPredicate {
148 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
149 CodeGenDAGPatterns &CGP;
151 typedef std::pair<unsigned, std::string> CodeLine;
152 typedef std::vector<CodeLine> CodeList;
153 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
155 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
156 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
157 const PatternToMatch *LHS = LHSPair.first;
158 const PatternToMatch *RHS = RHSPair.first;
160 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
161 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
162 LHSSize += LHS->getAddedComplexity();
163 RHSSize += RHS->getAddedComplexity();
164 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
165 if (LHSSize < RHSSize) return false;
167 // If the patterns have equal complexity, compare generated instruction cost
168 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
169 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
170 if (LHSCost < RHSCost) return true;
171 if (LHSCost > RHSCost) return false;
173 return getResultPatternSize(LHS->getDstPattern(), CGP) <
174 getResultPatternSize(RHS->getDstPattern(), CGP);
178 /// getRegisterValueType - Look up and return the ValueType of the specified
179 /// register. If the register is a member of multiple register classes which
180 /// have different associated types, return MVT::Other.
181 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
182 bool FoundRC = false;
183 MVT::SimpleValueType VT = MVT::Other;
184 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
185 std::vector<CodeGenRegisterClass>::const_iterator RC;
186 std::vector<Record*>::const_iterator Element;
188 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
189 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
190 if (Element != (*RC).Elements.end()) {
193 VT = (*RC).getValueTypeNum(0);
196 if (VT != (*RC).getValueTypeNum(0)) {
197 // Types of the RC's do not agree. Return MVT::Other. The
198 // target is responsible for handling this.
208 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
209 /// type information from it.
210 static void RemoveAllTypes(TreePatternNode *N) {
213 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
214 RemoveAllTypes(N->getChild(i));
217 /// NodeHasProperty - return true if TreePatternNode has the specified
219 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
220 CodeGenDAGPatterns &CGP) {
222 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
224 return CP->hasProperty(Property);
227 Record *Operator = N->getOperator();
228 if (!Operator->isSubClassOf("SDNode")) return false;
230 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
233 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
234 CodeGenDAGPatterns &CGP) {
235 if (NodeHasProperty(N, Property, CGP))
238 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
239 TreePatternNode *Child = N->getChild(i);
240 if (PatternHasProperty(Child, Property, CGP))
247 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
248 return CGP.getSDNodeInfo(Op).getEnumName();
252 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
253 bool isStore = !N->isLeaf() &&
254 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
255 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
258 bool HasChain = false;
259 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
260 TreePatternNode *Child = N->getChild(i);
261 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
269 //===----------------------------------------------------------------------===//
270 // Node Transformation emitter implementation.
272 void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
273 // Walk the pattern fragments, adding them to a map, which sorts them by
275 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
276 NXsByNameTy NXsByName;
278 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
280 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
282 OS << "\n// Node transformations.\n";
284 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
286 Record *SDNode = I->second.first;
287 std::string Code = I->second.second;
289 if (Code.empty()) continue; // Empty code? Skip it.
291 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
292 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
294 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
296 if (ClassName != "SDNode")
297 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
298 OS << Code << "\n}\n";
302 //===----------------------------------------------------------------------===//
303 // Predicate emitter implementation.
306 void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
307 OS << "\n// Predicate functions.\n";
309 // Walk the pattern fragments, adding them to a map, which sorts them by
311 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
312 PFsByNameTy PFsByName;
314 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
316 PFsByName.insert(std::make_pair(I->first->getName(), *I));
319 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
321 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
322 TreePattern *P = I->second.second;
324 // If there is a code init for this fragment, emit the predicate code.
325 std::string Code = PatFragRecord->getValueAsCode("Predicate");
326 if (Code.empty()) continue;
328 if (P->getOnlyTree()->isLeaf())
329 OS << "inline bool Predicate_" << PatFragRecord->getName()
330 << "(SDNode *N) {\n";
332 std::string ClassName =
333 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
334 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
336 OS << "inline bool Predicate_" << PatFragRecord->getName()
337 << "(SDNode *" << C2 << ") {\n";
338 if (ClassName != "SDNode")
339 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
341 OS << Code << "\n}\n";
348 //===----------------------------------------------------------------------===//
349 // PatternCodeEmitter implementation.
351 class PatternCodeEmitter {
353 CodeGenDAGPatterns &CGP;
356 std::string PredicateCheck;
359 // Instruction selector pattern.
360 TreePatternNode *Pattern;
361 // Matched instruction.
362 TreePatternNode *Instruction;
364 // Node to name mapping
365 std::map<std::string, std::string> VariableMap;
366 // Node to operator mapping
367 std::map<std::string, Record*> OperatorMap;
368 // Name of the folded node which produces a flag.
369 std::pair<std::string, unsigned> FoldedFlag;
370 // Names of all the folded nodes which produce chains.
371 std::vector<std::pair<std::string, unsigned> > FoldedChains;
372 // Original input chain(s).
373 std::vector<std::pair<std::string, std::string> > OrigChains;
374 std::set<std::string> Duplicates;
376 /// LSI - Load/Store information.
377 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
378 /// for each memory access. This facilitates the use of AliasAnalysis in
380 std::vector<std::string> LSI;
382 /// GeneratedCode - This is the buffer that we emit code to. The first int
383 /// indicates whether this is an exit predicate (something that should be
384 /// tested, and if true, the match fails) [when 1], or normal code to emit
385 /// [when 0], or initialization code to emit [when 2].
386 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
387 /// GeneratedDecl - This is the set of all SDValue declarations needed for
388 /// the set of patterns for each top-level opcode.
389 std::set<std::string> &GeneratedDecl;
390 /// TargetOpcodes - The target specific opcodes used by the resulting
392 std::vector<std::string> &TargetOpcodes;
393 std::vector<std::string> &TargetVTs;
394 /// OutputIsVariadic - Records whether the instruction output pattern uses
395 /// variable_ops. This requires that the Emit function be passed an
396 /// additional argument to indicate where the input varargs operands
398 bool &OutputIsVariadic;
399 /// NumInputRootOps - Records the number of operands the root node of the
400 /// input pattern has. This information is used in the generated code to
401 /// pass to Emit functions when variable_ops processing is needed.
402 unsigned &NumInputRootOps;
404 std::string ChainName;
409 void emitCheck(const std::string &S) {
411 GeneratedCode.push_back(std::make_pair(1, S));
413 void emitCode(const std::string &S) {
415 GeneratedCode.push_back(std::make_pair(0, S));
417 void emitInit(const std::string &S) {
419 GeneratedCode.push_back(std::make_pair(2, S));
421 void emitDecl(const std::string &S) {
422 assert(!S.empty() && "Invalid declaration");
423 GeneratedDecl.insert(S);
425 void emitOpcode(const std::string &Opc) {
426 TargetOpcodes.push_back(Opc);
429 void emitVT(const std::string &VT) {
430 TargetVTs.push_back(VT);
434 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
435 TreePatternNode *pattern, TreePatternNode *instr,
436 std::vector<std::pair<unsigned, std::string> > &gc,
437 std::set<std::string> &gd,
438 std::vector<std::string> &to,
439 std::vector<std::string> &tv,
442 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
443 GeneratedCode(gc), GeneratedDecl(gd),
444 TargetOpcodes(to), TargetVTs(tv),
445 OutputIsVariadic(oiv), NumInputRootOps(niro),
446 TmpNo(0), OpcNo(0), VTNo(0) {}
448 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
449 /// if the match fails. At this point, we already know that the opcode for N
450 /// matches, and the SDNode for the result has the RootName specified name.
451 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
452 const std::string &RootName, const std::string &ChainSuffix,
455 // Save loads/stores matched by a pattern.
456 if (!N->isLeaf() && N->getName().empty()) {
457 if (NodeHasProperty(N, SDNPMemOperand, CGP))
458 LSI.push_back(RootName);
461 bool isRoot = (P == NULL);
462 // Emit instruction predicates. Each predicate is just a string for now.
464 // Record input varargs info.
465 NumInputRootOps = N->getNumChildren();
467 if (DisablePatternForFastISel(N, CGP))
468 emitCheck("OptLevel != CodeGenOpt::None");
470 emitCheck(PredicateCheck);
474 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
475 emitCheck("cast<ConstantSDNode>(" + RootName +
476 ")->getSExtValue() == INT64_C(" +
477 itostr(II->getValue()) + ")");
479 } else if (!NodeIsComplexPattern(N)) {
480 assert(0 && "Cannot match this as a leaf value!");
485 // If this node has a name associated with it, capture it in VariableMap. If
486 // we already saw this in the pattern, emit code to verify dagness.
487 if (!N->getName().empty()) {
488 std::string &VarMapEntry = VariableMap[N->getName()];
489 if (VarMapEntry.empty()) {
490 VarMapEntry = RootName;
492 // If we get here, this is a second reference to a specific name. Since
493 // we already have checked that the first reference is valid, we don't
494 // have to recursively match it, just check that it's the same as the
495 // previously named thing.
496 emitCheck(VarMapEntry + " == " + RootName);
501 OperatorMap[N->getName()] = N->getOperator();
505 // Emit code to load the child nodes and match their contents recursively.
507 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
508 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
509 bool EmittedUseCheck = false;
514 // Multiple uses of actual result?
515 emitCheck(RootName + ".hasOneUse()");
516 EmittedUseCheck = true;
518 // If the immediate use can somehow reach this node through another
519 // path, then can't fold it either or it will create a cycle.
520 // e.g. In the following diagram, XX can reach ld through YY. If
521 // ld is folded into XX, then YY is both a predecessor and a successor
531 bool NeedCheck = P != Pattern;
533 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
535 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
536 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
537 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
538 PInfo.getNumOperands() > 1 ||
539 PInfo.hasProperty(SDNPHasChain) ||
540 PInfo.hasProperty(SDNPInFlag) ||
541 PInfo.hasProperty(SDNPOptInFlag);
545 std::string ParentName(RootName.begin(), RootName.end()-1);
546 emitCheck("IsLegalAndProfitableToFold(" + RootName +
547 ".getNode(), " + ParentName + ".getNode(), N.getNode())");
554 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
555 "IsChainCompatible(" + ChainName + ".getNode(), " +
556 RootName + ".getNode()))");
557 OrigChains.push_back(std::make_pair(ChainName, RootName));
560 ChainName = "Chain" + ChainSuffix;
561 emitInit("SDValue " + ChainName + " = " + RootName +
566 // Don't fold any node which reads or writes a flag and has multiple uses.
567 // FIXME: We really need to separate the concepts of flag and "glue". Those
568 // real flag results, e.g. X86CMP output, can have multiple uses.
569 // FIXME: If the optional incoming flag does not exist. Then it is ok to
572 (PatternHasProperty(N, SDNPInFlag, CGP) ||
573 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
574 PatternHasProperty(N, SDNPOutFlag, CGP))) {
575 if (!EmittedUseCheck) {
576 // Multiple uses of actual result?
577 emitCheck(RootName + ".hasOneUse()");
581 // If there are node predicates for this, emit the calls.
582 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
583 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
585 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
586 // a constant without a predicate fn that has more that one bit set, handle
587 // this as a special case. This is usually for targets that have special
588 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
589 // handling stuff). Using these instructions is often far more efficient
590 // than materializing the constant. Unfortunately, both the instcombiner
591 // and the dag combiner can often infer that bits are dead, and thus drop
592 // them from the mask in the dag. For example, it might turn 'AND X, 255'
593 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
596 (N->getOperator()->getName() == "and" ||
597 N->getOperator()->getName() == "or") &&
598 N->getChild(1)->isLeaf() &&
599 N->getChild(1)->getPredicateFns().empty()) {
600 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
601 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
602 emitInit("SDValue " + RootName + "0" + " = " +
603 RootName + ".getOperand(" + utostr(0) + ");");
604 emitInit("SDValue " + RootName + "1" + " = " +
605 RootName + ".getOperand(" + utostr(1) + ");");
607 unsigned NTmp = TmpNo++;
608 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
609 " = dyn_cast<ConstantSDNode>(" + RootName + "1);");
610 emitCheck("Tmp" + utostr(NTmp));
611 const char *MaskPredicate = N->getOperator()->getName() == "or"
612 ? "CheckOrMask(" : "CheckAndMask(";
613 emitCheck(MaskPredicate + RootName + "0, Tmp" + utostr(NTmp) +
614 ", INT64_C(" + itostr(II->getValue()) + "))");
616 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
617 ChainSuffix + utostr(0), FoundChain);
623 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
624 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
625 RootName + ".getOperand(" +utostr(OpNo) + ");");
627 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
628 ChainSuffix + utostr(OpNo), FoundChain);
631 // Handle cases when root is a complex pattern.
632 const ComplexPattern *CP;
633 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
634 std::string Fn = CP->getSelectFunc();
635 unsigned NumOps = CP->getNumOperands();
636 for (unsigned i = 0; i < NumOps; ++i) {
637 emitDecl("CPTmp" + RootName + "_" + utostr(i));
638 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
640 if (CP->hasProperty(SDNPHasChain)) {
641 emitDecl("CPInChain");
642 emitDecl("Chain" + ChainSuffix);
643 emitCode("SDValue CPInChain;");
644 emitCode("SDValue Chain" + ChainSuffix + ";");
647 std::string Code = Fn + "(" + RootName + ", " + RootName;
648 for (unsigned i = 0; i < NumOps; i++)
649 Code += ", CPTmp" + RootName + "_" + utostr(i);
650 if (CP->hasProperty(SDNPHasChain)) {
651 ChainName = "Chain" + ChainSuffix;
652 Code += ", CPInChain, Chain" + ChainSuffix;
654 emitCheck(Code + ")");
658 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
659 const std::string &RootName,
660 const std::string &ParentRootName,
661 const std::string &ChainSuffix, bool &FoundChain) {
662 if (!Child->isLeaf()) {
663 // If it's not a leaf, recursively match.
664 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
665 emitCheck(RootName + ".getOpcode() == " +
666 CInfo.getEnumName());
667 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
668 bool HasChain = false;
669 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
671 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
673 if (NodeHasProperty(Child, SDNPOutFlag, CGP) ||
674 NodeHasProperty(Child, SDNPOutI1, CGP)) {
675 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
676 "Pattern folded multiple nodes which produce flags?");
677 FoldedFlag = std::make_pair(RootName,
678 CInfo.getNumResults() + (unsigned)HasChain);
681 // If this child has a name associated with it, capture it in VarMap. If
682 // we already saw this in the pattern, emit code to verify dagness.
683 if (!Child->getName().empty()) {
684 std::string &VarMapEntry = VariableMap[Child->getName()];
685 if (VarMapEntry.empty()) {
686 VarMapEntry = RootName;
688 // If we get here, this is a second reference to a specific name.
689 // Since we already have checked that the first reference is valid,
690 // we don't have to recursively match it, just check that it's the
691 // same as the previously named thing.
692 emitCheck(VarMapEntry + " == " + RootName);
693 Duplicates.insert(RootName);
698 // Handle leaves of various types.
699 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
700 Record *LeafRec = DI->getDef();
701 if (LeafRec->isSubClassOf("RegisterClass") ||
702 LeafRec->getName() == "ptr_rc") {
703 // Handle register references. Nothing to do here.
704 } else if (LeafRec->isSubClassOf("Register")) {
705 // Handle register references.
706 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
707 // Handle complex pattern.
708 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
709 std::string Fn = CP->getSelectFunc();
710 unsigned NumOps = CP->getNumOperands();
711 for (unsigned i = 0; i < NumOps; ++i) {
712 emitDecl("CPTmp" + RootName + "_" + utostr(i));
713 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
715 if (CP->hasProperty(SDNPHasChain)) {
716 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
717 FoldedChains.push_back(std::make_pair("CPInChain",
718 PInfo.getNumResults()));
719 ChainName = "Chain" + ChainSuffix;
720 emitDecl("CPInChain");
722 emitCode("SDValue CPInChain;");
723 emitCode("SDValue " + ChainName + ";");
726 std::string Code = Fn + "(";
727 if (CP->hasAttribute(CPAttrParentAsRoot)) {
728 Code += ParentRootName + ", ";
732 if (CP->hasProperty(SDNPHasChain)) {
733 std::string ParentName(RootName.begin(), RootName.end()-1);
734 Code += ParentName + ", ";
737 for (unsigned i = 0; i < NumOps; i++)
738 Code += ", CPTmp" + RootName + "_" + utostr(i);
739 if (CP->hasProperty(SDNPHasChain))
740 Code += ", CPInChain, Chain" + ChainSuffix;
741 emitCheck(Code + ")");
742 } else if (LeafRec->getName() == "srcvalue") {
743 // Place holder for SRCVALUE nodes. Nothing to do here.
744 } else if (LeafRec->isSubClassOf("ValueType")) {
745 // Make sure this is the specified value type.
746 emitCheck("cast<VTSDNode>(" + RootName +
747 ")->getVT() == MVT::" + LeafRec->getName());
748 } else if (LeafRec->isSubClassOf("CondCode")) {
749 // Make sure this is the specified cond code.
750 emitCheck("cast<CondCodeSDNode>(" + RootName +
751 ")->get() == ISD::" + LeafRec->getName());
757 assert(0 && "Unknown leaf type!");
760 // If there are node predicates for this, emit the calls.
761 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
762 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
764 } else if (IntInit *II =
765 dynamic_cast<IntInit*>(Child->getLeafValue())) {
766 unsigned NTmp = TmpNo++;
767 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
768 " = dyn_cast<ConstantSDNode>("+
770 emitCheck("Tmp" + utostr(NTmp));
771 unsigned CTmp = TmpNo++;
772 emitCode("int64_t CN"+ utostr(CTmp) +
773 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
774 emitCheck("CN" + utostr(CTmp) + " == "
775 "INT64_C(" +itostr(II->getValue()) + ")");
780 assert(0 && "Unknown leaf type!");
785 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
786 /// we actually have to build a DAG!
787 std::vector<std::string>
788 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
789 bool InFlagDecled, bool ResNodeDecled,
790 bool LikeLeaf = false, bool isRoot = false) {
791 // List of arguments of getTargetNode() or SelectNodeTo().
792 std::vector<std::string> NodeOps;
793 // This is something selected from the pattern we matched.
794 if (!N->getName().empty()) {
795 const std::string &VarName = N->getName();
796 std::string Val = VariableMap[VarName];
797 bool ModifiedVal = false;
799 cerr << "Variable '" << VarName << " referenced but not defined "
800 << "and not caught earlier!\n";
803 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
804 // Already selected this operand, just return the tmpval.
805 NodeOps.push_back(Val);
809 const ComplexPattern *CP;
810 unsigned ResNo = TmpNo++;
811 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
812 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
813 std::string CastType;
814 std::string TmpVar = "Tmp" + utostr(ResNo);
815 switch (N->getTypeNum(0)) {
817 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
818 << " type as an immediate constant. Aborting\n";
820 case MVT::i1: CastType = "bool"; break;
821 case MVT::i8: CastType = "unsigned char"; break;
822 case MVT::i16: CastType = "unsigned short"; break;
823 case MVT::i32: CastType = "unsigned"; break;
824 case MVT::i64: CastType = "uint64_t"; break;
826 emitCode("SDValue " + TmpVar +
827 " = CurDAG->getTargetConstant(((" + CastType +
828 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
829 getEnumName(N->getTypeNum(0)) + ");");
830 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
831 // value if used multiple times by this pattern result.
834 NodeOps.push_back(Val);
835 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
836 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
837 std::string TmpVar = "Tmp" + utostr(ResNo);
838 emitCode("SDValue " + TmpVar +
839 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
840 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
841 Val + ")->getValueType(0));");
842 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
843 // value if used multiple times by this pattern result.
846 NodeOps.push_back(Val);
847 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
848 Record *Op = OperatorMap[N->getName()];
849 // Transform ExternalSymbol to TargetExternalSymbol
850 if (Op && Op->getName() == "externalsym") {
851 std::string TmpVar = "Tmp"+utostr(ResNo);
852 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
853 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
854 Val + ")->getSymbol(), " +
855 getEnumName(N->getTypeNum(0)) + ");");
856 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
857 // this value if used multiple times by this pattern result.
861 NodeOps.push_back(Val);
862 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
863 || N->getOperator()->getName() == "tglobaltlsaddr")) {
864 Record *Op = OperatorMap[N->getName()];
865 // Transform GlobalAddress to TargetGlobalAddress
866 if (Op && (Op->getName() == "globaladdr" ||
867 Op->getName() == "globaltlsaddr")) {
868 std::string TmpVar = "Tmp" + utostr(ResNo);
869 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
870 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
871 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
873 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
874 // this value if used multiple times by this pattern result.
878 NodeOps.push_back(Val);
879 } else if (!N->isLeaf()
880 && (N->getOperator()->getName() == "texternalsym"
881 || N->getOperator()->getName() == "tconstpool")) {
882 // Do not rewrite the variable name, since we don't generate a new
884 NodeOps.push_back(Val);
885 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
886 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
887 NodeOps.push_back("CPTmp" + Val + "_" + utostr(i));
890 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
891 // node even if it isn't one. Don't select it.
893 if (isRoot && N->isLeaf()) {
894 emitCode("ReplaceUses(N, " + Val + ");");
895 emitCode("return NULL;");
898 NodeOps.push_back(Val);
902 VariableMap[VarName] = Val;
907 // If this is an explicit register reference, handle it.
908 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
909 unsigned ResNo = TmpNo++;
910 if (DI->getDef()->isSubClassOf("Register")) {
911 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
912 getQualifiedName(DI->getDef()) + ", " +
913 getEnumName(N->getTypeNum(0)) + ");");
914 NodeOps.push_back("Tmp" + utostr(ResNo));
916 } else if (DI->getDef()->getName() == "zero_reg") {
917 emitCode("SDValue Tmp" + utostr(ResNo) +
918 " = CurDAG->getRegister(0, " +
919 getEnumName(N->getTypeNum(0)) + ");");
920 NodeOps.push_back("Tmp" + utostr(ResNo));
922 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
923 // Handle a reference to a register class. This is used
924 // in COPY_TO_SUBREG instructions.
925 emitCode("SDValue Tmp" + utostr(ResNo) +
926 " = CurDAG->getTargetConstant(" +
927 getQualifiedName(DI->getDef()) + "RegClassID, " +
929 NodeOps.push_back("Tmp" + utostr(ResNo));
932 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
933 unsigned ResNo = TmpNo++;
934 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
935 emitCode("SDValue Tmp" + utostr(ResNo) +
936 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
937 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
938 NodeOps.push_back("Tmp" + utostr(ResNo));
945 assert(0 && "Unknown leaf type!");
949 Record *Op = N->getOperator();
950 if (Op->isSubClassOf("Instruction")) {
951 const CodeGenTarget &CGT = CGP.getTargetInfo();
952 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
953 const DAGInstruction &Inst = CGP.getInstruction(Op);
954 const TreePattern *InstPat = Inst.getPattern();
955 // FIXME: Assume actual pattern comes before "implicit".
956 TreePatternNode *InstPatNode =
957 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
958 : (InstPat ? InstPat->getTree(0) : NULL);
959 if (InstPatNode && !InstPatNode->isLeaf() &&
960 InstPatNode->getOperator()->getName() == "set") {
961 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
963 bool IsVariadic = isRoot && II.isVariadic;
964 // FIXME: fix how we deal with physical register operands.
965 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
966 bool HasImpResults = isRoot && DstRegs.size() > 0;
967 bool NodeHasOptInFlag = isRoot &&
968 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
969 bool NodeHasInFlag = isRoot &&
970 PatternHasProperty(Pattern, SDNPInFlag, CGP);
971 bool NodeHasOutFlag = isRoot &&
972 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
973 bool NodeHasInI1 = isRoot &&
974 PatternHasProperty(Pattern, SDNPInI1, CGP);
975 bool NodeHasOutI1 = isRoot &&
976 PatternHasProperty(Pattern, SDNPOutI1, CGP);
977 bool NodeHasChain = InstPatNode &&
978 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
979 bool InputHasChain = isRoot &&
980 NodeHasProperty(Pattern, SDNPHasChain, CGP);
981 unsigned NumResults = Inst.getNumResults();
982 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
984 // Record output varargs info.
985 OutputIsVariadic = IsVariadic;
987 if (NodeHasOptInFlag) {
988 emitCode("bool HasInFlag = "
989 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
992 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
994 // How many results is this pattern expected to produce?
995 unsigned NumPatResults = 0;
996 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
997 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
998 if (VT != MVT::isVoid && VT != MVT::Flag)
1002 if (OrigChains.size() > 0) {
1003 // The original input chain is being ignored. If it is not just
1004 // pointing to the op that's being folded, we should create a
1005 // TokenFactor with it and the chain of the folded op as the new chain.
1006 // We could potentially be doing multiple levels of folding, in that
1007 // case, the TokenFactor can have more operands.
1008 emitCode("SmallVector<SDValue, 8> InChains;");
1009 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1010 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1011 OrigChains[i].second + ".getNode()) {");
1012 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1015 emitCode("InChains.push_back(" + ChainName + ");");
1016 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1017 "N.getDebugLoc(), MVT::Other, "
1018 "&InChains[0], InChains.size());");
1020 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1021 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1025 // Loop over all of the operands of the instruction pattern, emitting code
1026 // to fill them all in. The node 'N' usually has number children equal to
1027 // the number of input operands of the instruction. However, in cases
1028 // where there are predicate operands for an instruction, we need to fill
1029 // in the 'execute always' values. Match up the node operands to the
1030 // instruction operands to do this.
1031 std::vector<std::string> AllOps;
1032 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1033 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1034 std::vector<std::string> Ops;
1036 // Determine what to emit for this operand.
1037 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1038 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1039 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1040 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1041 // This is a predicate or optional def operand; emit the
1042 // 'default ops' operands.
1043 const DAGDefaultOperand &DefaultOp =
1044 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1045 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1046 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1047 InFlagDecled, ResNodeDecled);
1048 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1051 // Otherwise this is a normal operand or a predicate operand without
1052 // 'execute always'; emit it.
1053 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1054 InFlagDecled, ResNodeDecled);
1055 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1060 // Emit all the chain and CopyToReg stuff.
1061 bool ChainEmitted = NodeHasChain;
1062 // InFlag and InI1 cannot both be set (checked in
1063 // CodeGenDAGPatterns), so use the same variables for both.
1064 if (NodeHasInFlag || HasImpInputs || NodeHasInI1)
1065 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1066 InFlagDecled, ResNodeDecled, true);
1067 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs ||
1069 if (!InFlagDecled) {
1070 emitCode("SDValue InFlag(0, 0);");
1071 InFlagDecled = true;
1073 if (NodeHasOptInFlag) {
1074 emitCode("if (HasInFlag) {");
1075 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1080 unsigned ResNo = TmpNo++;
1082 unsigned OpsNo = OpcNo;
1083 std::string CodePrefix;
1084 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1085 std::deque<std::string> After;
1086 std::string NodeName;
1088 NodeName = "Tmp" + utostr(ResNo);
1089 CodePrefix = "SDValue " + NodeName + "(";
1091 NodeName = "ResNode";
1092 if (!ResNodeDecled) {
1093 CodePrefix = "SDNode *" + NodeName + " = ";
1094 ResNodeDecled = true;
1096 CodePrefix = NodeName + " = ";
1099 std::string Code = "Opc" + utostr(OpcNo);
1101 if (!isRoot || (InputHasChain && !NodeHasChain))
1102 // For call to "getTargetNode()".
1103 Code += ", N.getDebugLoc()";
1105 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1107 // Output order: results, chain, flags
1109 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1110 Code += ", VT" + utostr(VTNo);
1111 emitVT(getEnumName(N->getTypeNum(0)));
1113 // Add types for implicit results in physical registers, scheduler will
1114 // care of adding copyfromreg nodes.
1115 for (unsigned i = 0; i < NumDstRegs; i++) {
1116 Record *RR = DstRegs[i];
1117 if (RR->isSubClassOf("Register")) {
1118 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1119 Code += ", " + getEnumName(RVT);
1123 Code += ", MVT::Other";
1124 if (NodeHasOutFlag || (NodeHasOutI1 && !CGT.supportsHasI1()))
1125 Code += ", MVT::Flag";
1129 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1130 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1133 // Figure out whether any operands at the end of the op list are not
1134 // part of the variable section.
1135 std::string EndAdjust;
1136 if (NodeHasInFlag || HasImpInputs)
1137 EndAdjust = "-1"; // Always has one flag.
1138 else if (NodeHasOptInFlag)
1139 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1141 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1142 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1144 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1148 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1150 if (II.mayLoad | II.mayStore) {
1151 std::vector<std::string>::const_iterator mi, mie;
1152 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1153 std::string LSIName = "LSI_" + *mi;
1154 emitCode("SDValue " + LSIName + " = "
1155 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1156 *mi + ")->getMemOperand());");
1158 emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"yellow\");");
1159 emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"black\");");
1162 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + LSIName + ");");
1164 AllOps.push_back(LSIName);
1170 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1172 AllOps.push_back(ChainName);
1176 if (NodeHasInFlag || HasImpInputs)
1177 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1178 else if (NodeHasOptInFlag) {
1179 emitCode("if (HasInFlag)");
1180 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1182 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1184 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs ||
1186 AllOps.push_back("InFlag");
1188 unsigned NumOps = AllOps.size();
1190 if (!NodeHasOptInFlag && NumOps < 4) {
1191 for (unsigned i = 0; i != NumOps; ++i)
1192 Code += ", " + AllOps[i];
1194 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1195 for (unsigned i = 0; i != NumOps; ++i) {
1196 OpsCode += AllOps[i];
1200 emitCode(OpsCode + " };");
1201 Code += ", Ops" + utostr(OpsNo) + ", ";
1202 if (NodeHasOptInFlag) {
1203 Code += "HasInFlag ? ";
1204 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1206 Code += utostr(NumOps);
1213 std::vector<std::string> ReplaceFroms;
1214 std::vector<std::string> ReplaceTos;
1216 NodeOps.push_back("Tmp" + utostr(ResNo));
1219 if (NodeHasOutFlag || NodeHasOutI1) {
1220 if (!InFlagDecled) {
1221 After.push_back("SDValue InFlag(ResNode, " +
1222 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1224 InFlagDecled = true;
1226 After.push_back("InFlag = SDValue(ResNode, " +
1227 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1231 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1232 ReplaceFroms.push_back("SDValue(" +
1233 FoldedChains[j].first + ".getNode(), " +
1234 utostr(FoldedChains[j].second) +
1236 ReplaceTos.push_back("SDValue(ResNode, " +
1237 utostr(NumResults+NumDstRegs) + ")");
1240 if (NodeHasOutFlag || NodeHasOutI1) {
1241 if (FoldedFlag.first != "") {
1242 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first +
1244 utostr(FoldedFlag.second) + ")");
1245 ReplaceTos.push_back("InFlag");
1247 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP) ||
1248 NodeHasProperty(Pattern, SDNPOutI1, CGP));
1249 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1250 utostr(NumPatResults + (unsigned)InputHasChain)
1252 ReplaceTos.push_back("InFlag");
1256 if (!ReplaceFroms.empty() && InputHasChain) {
1257 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1258 utostr(NumPatResults) + ")");
1259 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1260 ChainName + ".getResNo()" + ")");
1261 ChainAssignmentNeeded |= NodeHasChain;
1264 // User does not expect the instruction would produce a chain!
1265 if ((!InputHasChain && NodeHasChain) &&
1266 (NodeHasOutFlag || NodeHasOutI1)) {
1268 } else if (InputHasChain && !NodeHasChain) {
1269 // One of the inner node produces a chain.
1270 if (NodeHasOutFlag) {
1271 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1272 utostr(NumPatResults+1) +
1274 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1276 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1277 utostr(NumPatResults) + ")");
1278 ReplaceTos.push_back(ChainName);
1282 if (ChainAssignmentNeeded) {
1283 // Remember which op produces the chain.
1284 std::string ChainAssign;
1286 ChainAssign = ChainName + " = SDValue(" + NodeName +
1287 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1289 ChainAssign = ChainName + " = SDValue(" + NodeName +
1290 ", " + utostr(NumResults+NumDstRegs) + ");";
1292 After.push_front(ChainAssign);
1295 if (ReplaceFroms.size() == 1) {
1296 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1297 ReplaceTos[0] + ");");
1298 } else if (!ReplaceFroms.empty()) {
1299 After.push_back("const SDValue Froms[] = {");
1300 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1301 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1302 After.push_back("};");
1303 After.push_back("const SDValue Tos[] = {");
1304 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1305 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1306 After.push_back("};");
1307 After.push_back("ReplaceUses(Froms, Tos, " +
1308 itostr(ReplaceFroms.size()) + ");");
1311 // We prefer to use SelectNodeTo since it avoids allocation when
1312 // possible and it avoids CSE map recalculation for the node's
1313 // users, however it's tricky to use in a non-root context.
1315 // We also don't use if the pattern replacement is being used to
1316 // jettison a chain result, since morphing the node in place
1317 // would leave users of the chain dangling.
1319 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1320 Code = "CurDAG->getTargetNode(" + Code;
1322 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1326 CodePrefix = "return ";
1328 After.push_back("return ResNode;");
1331 emitCode(CodePrefix + Code + ");");
1335 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1336 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1339 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1340 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1344 for (unsigned i = 0, e = After.size(); i != e; ++i)
1349 if (Op->isSubClassOf("SDNodeXForm")) {
1350 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1351 // PatLeaf node - the operand may or may not be a leaf node. But it should
1353 std::vector<std::string> Ops =
1354 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1355 ResNodeDecled, true);
1356 unsigned ResNo = TmpNo++;
1357 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1358 + "(" + Ops.back() + ".getNode());");
1359 NodeOps.push_back("Tmp" + utostr(ResNo));
1361 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1367 throw std::string("Unknown node in result pattern!");
1370 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1371 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1372 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1373 /// for, this returns true otherwise false if Pat has all types.
1374 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1375 const std::string &Prefix, bool isRoot = false) {
1377 if (Pat->getExtTypes() != Other->getExtTypes()) {
1378 // Move a type over from 'other' to 'pat'.
1379 Pat->setTypes(Other->getExtTypes());
1380 // The top level node type is checked outside of the select function.
1382 emitCheck(Prefix + ".getNode()->getValueType(0) == " +
1383 getName(Pat->getTypeNum(0)));
1388 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1389 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1390 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1391 Prefix + utostr(OpNo)))
1397 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1399 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1400 bool &ChainEmitted, bool &InFlagDecled,
1401 bool &ResNodeDecled, bool isRoot = false) {
1402 const CodeGenTarget &T = CGP.getTargetInfo();
1404 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1405 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1406 bool HasInI1 = NodeHasProperty(N, SDNPInI1, CGP);
1407 bool InFlagDefined = false;
1408 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1409 TreePatternNode *Child = N->getChild(i);
1410 if (!Child->isLeaf()) {
1411 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1412 InFlagDecled, ResNodeDecled);
1414 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1415 if (!Child->getName().empty()) {
1416 std::string Name = RootName + utostr(OpNo);
1417 if (Duplicates.find(Name) != Duplicates.end())
1418 // A duplicate! Do not emit a copy for this node.
1422 Record *RR = DI->getDef();
1423 if (RR->isSubClassOf("Register")) {
1424 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1425 if (RVT == MVT::Flag) {
1426 if (!InFlagDecled) {
1427 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1428 InFlagDecled = true;
1430 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1432 if (!ChainEmitted) {
1433 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1434 ChainName = "Chain";
1435 ChainEmitted = true;
1437 if (!InFlagDecled) {
1438 emitCode("SDValue InFlag(0, 0);");
1439 InFlagDecled = true;
1442 if (!ResNodeDecled) {
1443 emitCode("SDNode * ResNode;");
1445 if (T.supportsHasI1())
1446 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
1447 ", " + RootName + ".getDebugLoc()" +
1448 ", " + getEnumName(RVT) +
1449 ", " + getQualifiedName(RR) +
1450 ", " + RootName + utostr(OpNo) + ").getNode();");
1452 emitCode("ResNode = CurDAG->getCopyToReg(" + ChainName +
1453 ", " + RootName + ".getDebugLoc()" +
1454 ", " + getQualifiedName(RR) +
1455 ", " + RootName + utostr(OpNo) +
1456 ", InFlag).getNode();");
1457 InFlagDefined = true;
1459 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1460 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1461 ", " + RootName + ".getDebugLoc()" +
1462 ", " + getQualifiedName(RR) +
1463 ", " + RootName + utostr(OpNo) +
1464 ", InFlag).getNode();");
1466 emitCode(ChainName + " = SDValue(ResNode, 0);");
1467 emitCode("InFlag = SDValue(ResNode, 1);");
1468 ResNodeDecled = true;
1475 if (HasInFlag || (HasInI1 && !InFlagDefined)) {
1476 if (!InFlagDecled) {
1477 emitCode("SDValue InFlag = " + RootName +
1478 ".getOperand(" + utostr(OpNo) + ");");
1479 InFlagDecled = true;
1481 emitCode("InFlag = " + RootName +
1482 ".getOperand(" + utostr(OpNo) + ");");
1487 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1488 /// stream to match the pattern, and generate the code for the match if it
1489 /// succeeds. Returns true if the pattern is not guaranteed to match.
1490 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1491 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1492 std::set<std::string> &GeneratedDecl,
1493 std::vector<std::string> &TargetOpcodes,
1494 std::vector<std::string> &TargetVTs,
1495 bool &OutputIsVariadic,
1496 unsigned &NumInputRootOps) {
1497 OutputIsVariadic = false;
1498 NumInputRootOps = 0;
1500 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1501 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1502 GeneratedCode, GeneratedDecl,
1503 TargetOpcodes, TargetVTs,
1504 OutputIsVariadic, NumInputRootOps);
1506 // Emit the matcher, capturing named arguments in VariableMap.
1507 bool FoundChain = false;
1508 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1510 // TP - Get *SOME* tree pattern, we don't care which.
1511 TreePattern &TP = *CGP.pf_begin()->second;
1513 // At this point, we know that we structurally match the pattern, but the
1514 // types of the nodes may not match. Figure out the fewest number of type
1515 // comparisons we need to emit. For example, if there is only one integer
1516 // type supported by a target, there should be no type comparisons at all for
1517 // integer patterns!
1519 // To figure out the fewest number of type checks needed, clone the pattern,
1520 // remove the types, then perform type inference on the pattern as a whole.
1521 // If there are unresolved types, emit an explicit check for those types,
1522 // apply the type to the tree, then rerun type inference. Iterate until all
1523 // types are resolved.
1525 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1526 RemoveAllTypes(Pat);
1529 // Resolve/propagate as many types as possible.
1531 bool MadeChange = true;
1533 MadeChange = Pat->ApplyTypeConstraints(TP,
1534 true/*Ignore reg constraints*/);
1536 assert(0 && "Error: could not find consistent types for something we"
1537 " already decided was ok!");
1541 // Insert a check for an unresolved type and add it to the tree. If we find
1542 // an unresolved type to add a check for, this returns true and we iterate,
1543 // otherwise we are done.
1544 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1546 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1547 false, false, false, true);
1551 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1552 /// a line causes any of them to be empty, remove them and return true when
1554 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1555 std::vector<std::pair<unsigned, std::string> > > >
1557 bool ErasedPatterns = false;
1558 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1559 Patterns[i].second.pop_back();
1560 if (Patterns[i].second.empty()) {
1561 Patterns.erase(Patterns.begin()+i);
1563 ErasedPatterns = true;
1566 return ErasedPatterns;
1569 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1570 /// code together between the patterns.
1571 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1572 std::vector<std::pair<unsigned, std::string> > > >
1573 &Patterns, unsigned Indent,
1575 typedef std::pair<unsigned, std::string> CodeLine;
1576 typedef std::vector<CodeLine> CodeList;
1577 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1579 if (Patterns.empty()) return;
1581 // Figure out how many patterns share the next code line. Explicitly copy
1582 // FirstCodeLine so that we don't invalidate a reference when changing
1584 const CodeLine FirstCodeLine = Patterns.back().second.back();
1585 unsigned LastMatch = Patterns.size()-1;
1586 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1589 // If not all patterns share this line, split the list into two pieces. The
1590 // first chunk will use this line, the second chunk won't.
1591 if (LastMatch != 0) {
1592 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1593 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1595 // FIXME: Emit braces?
1596 if (Shared.size() == 1) {
1597 const PatternToMatch &Pattern = *Shared.back().first;
1598 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1599 Pattern.getSrcPattern()->print(OS);
1600 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1601 Pattern.getDstPattern()->print(OS);
1603 unsigned AddedComplexity = Pattern.getAddedComplexity();
1604 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1605 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1607 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1609 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1611 if (FirstCodeLine.first != 1) {
1612 OS << std::string(Indent, ' ') << "{\n";
1615 EmitPatterns(Shared, Indent, OS);
1616 if (FirstCodeLine.first != 1) {
1618 OS << std::string(Indent, ' ') << "}\n";
1621 if (Other.size() == 1) {
1622 const PatternToMatch &Pattern = *Other.back().first;
1623 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1624 Pattern.getSrcPattern()->print(OS);
1625 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1626 Pattern.getDstPattern()->print(OS);
1628 unsigned AddedComplexity = Pattern.getAddedComplexity();
1629 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1630 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1632 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1634 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1636 EmitPatterns(Other, Indent, OS);
1640 // Remove this code from all of the patterns that share it.
1641 bool ErasedPatterns = EraseCodeLine(Patterns);
1643 bool isPredicate = FirstCodeLine.first == 1;
1645 // Otherwise, every pattern in the list has this line. Emit it.
1648 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1650 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1652 // If the next code line is another predicate, and if all of the pattern
1653 // in this group share the same next line, emit it inline now. Do this
1654 // until we run out of common predicates.
1655 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1656 // Check that all of the patterns in Patterns end with the same predicate.
1657 bool AllEndWithSamePredicate = true;
1658 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1659 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1660 AllEndWithSamePredicate = false;
1663 // If all of the predicates aren't the same, we can't share them.
1664 if (!AllEndWithSamePredicate) break;
1666 // Otherwise we can. Emit it shared now.
1667 OS << " &&\n" << std::string(Indent+4, ' ')
1668 << Patterns.back().second.back().second;
1669 ErasedPatterns = EraseCodeLine(Patterns);
1676 EmitPatterns(Patterns, Indent, OS);
1679 OS << std::string(Indent-2, ' ') << "}\n";
1682 static std::string getLegalCName(std::string OpName) {
1683 std::string::size_type pos = OpName.find("::");
1684 if (pos != std::string::npos)
1685 OpName.replace(pos, 2, "_");
1689 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1690 const CodeGenTarget &Target = CGP.getTargetInfo();
1692 // Get the namespace to insert instructions into.
1693 std::string InstNS = Target.getInstNamespace();
1694 if (!InstNS.empty()) InstNS += "::";
1696 // Group the patterns by their top-level opcodes.
1697 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1698 // All unique target node emission functions.
1699 std::map<std::string, unsigned> EmitFunctions;
1700 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1701 E = CGP.ptm_end(); I != E; ++I) {
1702 const PatternToMatch &Pattern = *I;
1704 TreePatternNode *Node = Pattern.getSrcPattern();
1705 if (!Node->isLeaf()) {
1706 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1707 push_back(&Pattern);
1709 const ComplexPattern *CP;
1710 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1711 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1712 push_back(&Pattern);
1713 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1714 std::vector<Record*> OpNodes = CP->getRootNodes();
1715 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1716 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1717 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1721 cerr << "Unrecognized opcode '";
1723 cerr << "' on tree pattern '";
1724 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1730 // For each opcode, there might be multiple select functions, one per
1731 // ValueType of the node (or its first operand if it doesn't produce a
1732 // non-chain result.
1733 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1735 // Emit one Select_* method for each top-level opcode. We do this instead of
1736 // emitting one giant switch statement to support compilers where this will
1737 // result in the recursive functions taking less stack space.
1738 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1739 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1740 PBOI != E; ++PBOI) {
1741 const std::string &OpName = PBOI->first;
1742 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1743 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1745 // Split them into groups by type.
1746 std::map<MVT::SimpleValueType,
1747 std::vector<const PatternToMatch*> > PatternsByType;
1748 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1749 const PatternToMatch *Pat = PatternsOfOp[i];
1750 TreePatternNode *SrcPat = Pat->getSrcPattern();
1751 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1754 for (std::map<MVT::SimpleValueType,
1755 std::vector<const PatternToMatch*> >::iterator
1756 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1758 MVT::SimpleValueType OpVT = II->first;
1759 std::vector<const PatternToMatch*> &Patterns = II->second;
1760 typedef std::pair<unsigned, std::string> CodeLine;
1761 typedef std::vector<CodeLine> CodeList;
1762 typedef CodeList::iterator CodeListI;
1764 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1765 std::vector<std::vector<std::string> > PatternOpcodes;
1766 std::vector<std::vector<std::string> > PatternVTs;
1767 std::vector<std::set<std::string> > PatternDecls;
1768 std::vector<bool> OutputIsVariadicFlags;
1769 std::vector<unsigned> NumInputRootOpsCounts;
1770 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1771 CodeList GeneratedCode;
1772 std::set<std::string> GeneratedDecl;
1773 std::vector<std::string> TargetOpcodes;
1774 std::vector<std::string> TargetVTs;
1775 bool OutputIsVariadic;
1776 unsigned NumInputRootOps;
1777 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1778 TargetOpcodes, TargetVTs,
1779 OutputIsVariadic, NumInputRootOps);
1780 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1781 PatternDecls.push_back(GeneratedDecl);
1782 PatternOpcodes.push_back(TargetOpcodes);
1783 PatternVTs.push_back(TargetVTs);
1784 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1785 NumInputRootOpsCounts.push_back(NumInputRootOps);
1788 // Factor target node emission code (emitted by EmitResultCode) into
1789 // separate functions. Uniquing and share them among all instruction
1790 // selection routines.
1791 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1792 CodeList &GeneratedCode = CodeForPatterns[i].second;
1793 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1794 std::vector<std::string> &TargetVTs = PatternVTs[i];
1795 std::set<std::string> Decls = PatternDecls[i];
1796 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1797 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1798 std::vector<std::string> AddedInits;
1799 int CodeSize = (int)GeneratedCode.size();
1801 for (int j = CodeSize-1; j >= 0; --j) {
1802 if (LastPred == -1 && GeneratedCode[j].first == 1)
1804 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1805 AddedInits.push_back(GeneratedCode[j].second);
1808 std::string CalleeCode = "(const SDValue &N";
1809 std::string CallerCode = "(N";
1810 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1811 CalleeCode += ", unsigned Opc" + utostr(j);
1812 CallerCode += ", " + TargetOpcodes[j];
1814 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1815 CalleeCode += ", MVT VT" + utostr(j);
1816 CallerCode += ", " + TargetVTs[j];
1818 for (std::set<std::string>::iterator
1819 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1820 std::string Name = *I;
1821 CalleeCode += ", SDValue &" + Name;
1822 CallerCode += ", " + Name;
1825 if (OutputIsVariadic) {
1826 CalleeCode += ", unsigned NumInputRootOps";
1827 CallerCode += ", " + utostr(NumInputRootOps);
1832 // Prevent emission routines from being inlined to reduce selection
1833 // routines stack frame sizes.
1834 CalleeCode += "DISABLE_INLINE ";
1835 CalleeCode += "{\n";
1837 for (std::vector<std::string>::const_reverse_iterator
1838 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1839 CalleeCode += " " + *I + "\n";
1841 for (int j = LastPred+1; j < CodeSize; ++j)
1842 CalleeCode += " " + GeneratedCode[j].second + "\n";
1843 for (int j = LastPred+1; j < CodeSize; ++j)
1844 GeneratedCode.pop_back();
1845 CalleeCode += "}\n";
1847 // Uniquing the emission routines.
1848 unsigned EmitFuncNum;
1849 std::map<std::string, unsigned>::iterator EFI =
1850 EmitFunctions.find(CalleeCode);
1851 if (EFI != EmitFunctions.end()) {
1852 EmitFuncNum = EFI->second;
1854 EmitFuncNum = EmitFunctions.size();
1855 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1856 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1859 // Replace the emission code within selection routines with calls to the
1860 // emission functions.
1862 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1864 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1865 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1867 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1868 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1869 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1870 GeneratedCode.push_back(std::make_pair(0, "}"));
1871 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1873 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1877 std::string OpVTStr;
1878 if (OpVT == MVT::iPTR) {
1880 } else if (OpVT == MVT::iPTRAny) {
1881 OpVTStr = "_iPTRAny";
1882 } else if (OpVT == MVT::isVoid) {
1883 // Nodes with a void result actually have a first result type of either
1884 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1885 // void to this case, we handle it specially here.
1887 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1889 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1890 OpcodeVTMap.find(OpName);
1891 if (OpVTI == OpcodeVTMap.end()) {
1892 std::vector<std::string> VTSet;
1893 VTSet.push_back(OpVTStr);
1894 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1896 OpVTI->second.push_back(OpVTStr);
1898 // We want to emit all of the matching code now. However, we want to emit
1899 // the matches in order of minimal cost. Sort the patterns so the least
1900 // cost one is at the start.
1901 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1902 PatternSortingPredicate(CGP));
1904 // Scan the code to see if all of the patterns are reachable and if it is
1905 // possible that the last one might not match.
1906 bool mightNotMatch = true;
1907 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1908 CodeList &GeneratedCode = CodeForPatterns[i].second;
1909 mightNotMatch = false;
1911 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1912 if (GeneratedCode[j].first == 1) { // predicate.
1913 mightNotMatch = true;
1918 // If this pattern definitely matches, and if it isn't the last one, the
1919 // patterns after it CANNOT ever match. Error out.
1920 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1921 cerr << "Pattern '";
1922 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1923 cerr << "' is impossible to select!\n";
1928 // Loop through and reverse all of the CodeList vectors, as we will be
1929 // accessing them from their logical front, but accessing the end of a
1930 // vector is more efficient.
1931 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1932 CodeList &GeneratedCode = CodeForPatterns[i].second;
1933 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1936 // Next, reverse the list of patterns itself for the same reason.
1937 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1939 OS << "SDNode *Select_" << getLegalCName(OpName)
1940 << OpVTStr << "(const SDValue &N) {\n";
1942 // Emit all of the patterns now, grouped together to share code.
1943 EmitPatterns(CodeForPatterns, 2, OS);
1945 // If the last pattern has predicates (which could fail) emit code to
1946 // catch the case where nothing handles a pattern.
1947 if (mightNotMatch) {
1949 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1950 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1951 OpName != "ISD::INTRINSIC_VOID")
1952 OS << " CannotYetSelect(N);\n";
1954 OS << " CannotYetSelectIntrinsic(N);\n";
1956 OS << " return NULL;\n";
1962 // Emit boilerplate.
1963 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1964 << " std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());\n"
1965 << " SelectInlineAsmMemoryOperands(Ops);\n\n"
1967 << " std::vector<MVT> VTs;\n"
1968 << " VTs.push_back(MVT::Other);\n"
1969 << " VTs.push_back(MVT::Flag);\n"
1970 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, N.getDebugLoc(), "
1971 "VTs, &Ops[0], Ops.size());\n"
1972 << " return New.getNode();\n"
1975 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1976 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,\n"
1977 << " N.getValueType());\n"
1980 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1981 << " SDValue Chain = N.getOperand(0);\n"
1982 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1983 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1984 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,\n"
1985 << " MVT::Other, Tmp, Chain);\n"
1988 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1989 << " SDValue Chain = N.getOperand(0);\n"
1990 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1991 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1992 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,\n"
1993 << " MVT::Other, Tmp, Chain);\n"
1996 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1997 << " SDValue Chain = N.getOperand(0);\n"
1998 << " SDValue N1 = N.getOperand(1);\n"
1999 << " SDValue N2 = N.getOperand(2);\n"
2000 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
2001 << " CannotYetSelect(N);\n"
2003 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
2004 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
2005 << " SDValue Tmp1 = "
2006 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
2007 << " SDValue Tmp2 = "
2008 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
2009 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DECLARE,\n"
2010 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
2013 OS << "// The main instruction selector code.\n"
2014 << "SDNode *SelectCode(SDValue N) {\n"
2015 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT();\n"
2016 << " switch (N.getOpcode()) {\n"
2018 << " assert(!N.isMachineOpcode() && \"Node already selected!\");\n"
2020 << " case ISD::EntryToken: // These nodes remain the same.\n"
2021 << " case ISD::MEMOPERAND:\n"
2022 << " case ISD::BasicBlock:\n"
2023 << " case ISD::Register:\n"
2024 << " case ISD::HANDLENODE:\n"
2025 << " case ISD::TargetConstant:\n"
2026 << " case ISD::TargetConstantFP:\n"
2027 << " case ISD::TargetConstantPool:\n"
2028 << " case ISD::TargetFrameIndex:\n"
2029 << " case ISD::TargetExternalSymbol:\n"
2030 << " case ISD::TargetJumpTable:\n"
2031 << " case ISD::TargetGlobalTLSAddress:\n"
2032 << " case ISD::TargetGlobalAddress:\n"
2033 << " case ISD::TokenFactor:\n"
2034 << " case ISD::CopyFromReg:\n"
2035 << " case ISD::CopyToReg: {\n"
2036 << " return NULL;\n"
2038 << " case ISD::AssertSext:\n"
2039 << " case ISD::AssertZext: {\n"
2040 << " ReplaceUses(N, N.getOperand(0));\n"
2041 << " return NULL;\n"
2043 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
2044 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
2045 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
2046 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
2047 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
2049 // Loop over all of the case statements, emiting a call to each method we
2051 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
2052 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
2053 PBOI != E; ++PBOI) {
2054 const std::string &OpName = PBOI->first;
2055 // Potentially multiple versions of select for this opcode. One for each
2056 // ValueType of the node (or its first true operand if it doesn't produce a
2058 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2059 OpcodeVTMap.find(OpName);
2060 std::vector<std::string> &OpVTs = OpVTI->second;
2061 OS << " case " << OpName << ": {\n";
2062 // If we have only one variant and it's the default, elide the
2063 // switch. Marginally faster, and makes MSVC happier.
2064 if (OpVTs.size()==1 && OpVTs[0].empty()) {
2065 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2070 // Keep track of whether we see a pattern that has an iPtr result.
2071 bool HasPtrPattern = false;
2072 bool HasDefaultPattern = false;
2074 OS << " switch (NVT) {\n";
2075 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2076 std::string &VTStr = OpVTs[i];
2077 if (VTStr.empty()) {
2078 HasDefaultPattern = true;
2082 // If this is a match on iPTR: don't emit it directly, we need special
2084 if (VTStr == "_iPTR") {
2085 HasPtrPattern = true;
2088 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2089 << " return Select_" << getLegalCName(OpName)
2090 << VTStr << "(N);\n";
2092 OS << " default:\n";
2094 // If there is an iPTR result version of this pattern, emit it here.
2095 if (HasPtrPattern) {
2096 OS << " if (TLI.getPointerTy() == NVT)\n";
2097 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2099 if (HasDefaultPattern) {
2100 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2108 OS << " } // end of big switch.\n\n"
2109 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2110 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2111 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2112 << " CannotYetSelect(N);\n"
2114 << " CannotYetSelectIntrinsic(N);\n"
2116 << " return NULL;\n"
2119 OS << "void CannotYetSelect(SDValue N) DISABLE_INLINE {\n"
2120 << " cerr << \"Cannot yet select: \";\n"
2121 << " N.getNode()->dump(CurDAG);\n"
2122 << " cerr << '\\n';\n"
2126 OS << "void CannotYetSelectIntrinsic(SDValue N) DISABLE_INLINE {\n"
2127 << " cerr << \"Cannot yet select: \";\n"
2128 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2129 << "N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();\n"
2130 << " cerr << \"intrinsic %\"<< "
2131 << "Intrinsic::getName((Intrinsic::ID)iid);\n"
2132 << " cerr << '\\n';\n"
2137 void DAGISelEmitter::run(std::ostream &OS) {
2138 EmitSourceFileHeader("DAG Instruction Selector for the " +
2139 CGP.getTargetInfo().getName() + " target", OS);
2141 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2142 << "// *** instruction selector class. These functions are really "
2145 OS << "// Include standard, target-independent definitions and methods used\n"
2146 << "// by the instruction selector.\n";
2147 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
2149 EmitNodeTransforms(OS);
2150 EmitPredicateFunctions(OS);
2152 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
2153 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2155 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2156 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
2160 // At this point, we have full information about the 'Patterns' we need to
2161 // parse, both implicitly from instructions as well as from explicit pattern
2162 // definitions. Emit the resultant instruction selector.
2163 EmitInstructionSelector(OS);