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"
15 #include "DAGISelMatcher.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Debug.h"
20 #include "llvm/Support/MathExtras.h"
21 #include "llvm/Support/Debug.h"
28 GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
30 //===----------------------------------------------------------------------===//
31 // DAGISelEmitter Helper methods
34 /// getNodeName - The top level Select_* functions have an "SDNode* N"
35 /// argument. When expanding the pattern-matching code, the intermediate
36 /// variables have type SDValue. This function provides a uniform way to
37 /// reference the underlying "SDNode *" for both cases.
38 static std::string getNodeName(const std::string &S) {
39 if (S == "N") return S;
40 return S + ".getNode()";
43 /// getNodeValue - Similar to getNodeName, except it provides a uniform
44 /// way to access the SDValue for both cases.
45 static std::string getValueName(const std::string &S) {
46 if (S == "N") return "SDValue(N, 0)";
50 /// getPatternSize - Return the 'size' of this pattern. We want to match large
51 /// patterns before small ones. This is used to determine the size of a
53 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
54 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
56 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR ||
59 P->getExtTypeNum(0) == MVT::iPTRAny) &&
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 = P->getComplexPatternInfo(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->getPredicateFns().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 (Child->getComplexPatternInfo(CGP))
90 Size += getPatternSize(Child, CGP);
91 else if (!Child->getPredicateFns().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.usesCustomInserter)
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 typedef std::pair<unsigned, std::string> CodeLine;
143 typedef std::vector<CodeLine> CodeList;
144 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
146 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
147 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
148 const PatternToMatch *LHS = LHSPair.first;
149 const PatternToMatch *RHS = RHSPair.first;
151 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
152 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
153 LHSSize += LHS->getAddedComplexity();
154 RHSSize += RHS->getAddedComplexity();
155 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
156 if (LHSSize < RHSSize) return false;
158 // If the patterns have equal complexity, compare generated instruction cost
159 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
160 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
161 if (LHSCost < RHSCost) return true;
162 if (LHSCost > RHSCost) return false;
164 return getResultPatternSize(LHS->getDstPattern(), CGP) <
165 getResultPatternSize(RHS->getDstPattern(), CGP);
169 /// getRegisterValueType - Look up and return the ValueType of the specified
170 /// register. If the register is a member of multiple register classes which
171 /// have different associated types, return MVT::Other.
172 static MVT::SimpleValueType getRegisterValueType(Record *R,
173 const CodeGenTarget &T) {
174 bool FoundRC = false;
175 MVT::SimpleValueType VT = MVT::Other;
176 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
177 std::vector<CodeGenRegisterClass>::const_iterator RC;
178 std::vector<Record*>::const_iterator Element;
180 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
181 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
182 if (Element != (*RC).Elements.end()) {
185 VT = (*RC).getValueTypeNum(0);
188 if (VT != (*RC).getValueTypeNum(0)) {
189 // Types of the RC's do not agree. Return MVT::Other. The
190 // target is responsible for handling this.
199 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
200 return CGP.getSDNodeInfo(Op).getEnumName();
203 //===----------------------------------------------------------------------===//
204 // Node Transformation emitter implementation.
206 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
207 // Walk the pattern fragments, adding them to a map, which sorts them by
209 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
210 NXsByNameTy NXsByName;
212 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
214 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
216 OS << "\n// Node transformations.\n";
218 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
220 Record *SDNode = I->second.first;
221 std::string Code = I->second.second;
223 if (Code.empty()) continue; // Empty code? Skip it.
225 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
226 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
228 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
230 if (ClassName != "SDNode")
231 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
232 OS << Code << "\n}\n";
236 //===----------------------------------------------------------------------===//
237 // Predicate emitter implementation.
240 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
241 OS << "\n// Predicate functions.\n";
243 // Walk the pattern fragments, adding them to a map, which sorts them by
245 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
246 PFsByNameTy PFsByName;
248 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
250 PFsByName.insert(std::make_pair(I->first->getName(), *I));
253 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
255 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
256 TreePattern *P = I->second.second;
258 // If there is a code init for this fragment, emit the predicate code.
259 std::string Code = PatFragRecord->getValueAsCode("Predicate");
260 if (Code.empty()) continue;
262 if (P->getOnlyTree()->isLeaf())
263 OS << "inline bool Predicate_" << PatFragRecord->getName()
264 << "(SDNode *N) const {\n";
266 std::string ClassName =
267 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
268 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
270 OS << "inline bool Predicate_" << PatFragRecord->getName()
271 << "(SDNode *" << C2 << ") const {\n";
272 if (ClassName != "SDNode")
273 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
275 OS << Code << "\n}\n";
282 //===----------------------------------------------------------------------===//
283 // PatternCodeEmitter implementation.
285 class PatternCodeEmitter {
287 CodeGenDAGPatterns &CGP;
290 std::string PredicateCheck;
293 // Instruction selector pattern.
294 TreePatternNode *Pattern;
295 // Matched instruction.
296 TreePatternNode *Instruction;
298 // Node to name mapping
299 std::map<std::string, std::string> VariableMap;
300 // Name of the folded node which produces a flag.
301 std::pair<std::string, unsigned> FoldedFlag;
302 // Names of all the folded nodes which produce chains.
303 std::vector<std::pair<std::string, unsigned> > FoldedChains;
304 // Original input chain(s).
305 std::vector<std::pair<std::string, std::string> > OrigChains;
306 std::set<std::string> Duplicates;
308 /// LSI - Load/Store information.
309 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
310 /// for each memory access. This facilitates the use of AliasAnalysis in
312 std::vector<std::string> LSI;
314 /// GeneratedCode - This is the buffer that we emit code to. The first int
315 /// indicates whether this is an exit predicate (something that should be
316 /// tested, and if true, the match fails) [when 1], or normal code to emit
317 /// [when 0], or initialization code to emit [when 2].
318 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
319 /// GeneratedDecl - This is the set of all SDValue declarations needed for
320 /// the set of patterns for each top-level opcode.
321 std::set<std::string> &GeneratedDecl;
322 /// TargetOpcodes - The target specific opcodes used by the resulting
324 std::vector<std::string> &TargetOpcodes;
325 std::vector<std::string> &TargetVTs;
326 /// OutputIsVariadic - Records whether the instruction output pattern uses
327 /// variable_ops. This requires that the Emit function be passed an
328 /// additional argument to indicate where the input varargs operands
330 bool &OutputIsVariadic;
331 /// NumInputRootOps - Records the number of operands the root node of the
332 /// input pattern has. This information is used in the generated code to
333 /// pass to Emit functions when variable_ops processing is needed.
334 unsigned &NumInputRootOps;
336 std::string ChainName;
341 void emitCheck(const std::string &S) {
343 GeneratedCode.push_back(std::make_pair(1, S));
345 void emitCode(const std::string &S) {
347 GeneratedCode.push_back(std::make_pair(0, S));
349 void emitInit(const std::string &S) {
351 GeneratedCode.push_back(std::make_pair(2, S));
353 void emitDecl(const std::string &S) {
354 assert(!S.empty() && "Invalid declaration");
355 GeneratedDecl.insert(S);
357 void emitOpcode(const std::string &Opc) {
358 TargetOpcodes.push_back(Opc);
361 void emitVT(const std::string &VT) {
362 TargetVTs.push_back(VT);
366 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
367 TreePatternNode *pattern, TreePatternNode *instr,
368 std::vector<std::pair<unsigned, std::string> > &gc,
369 std::set<std::string> &gd,
370 std::vector<std::string> &to,
371 std::vector<std::string> &tv,
374 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
375 GeneratedCode(gc), GeneratedDecl(gd),
376 TargetOpcodes(to), TargetVTs(tv),
377 OutputIsVariadic(oiv), NumInputRootOps(niro),
378 TmpNo(0), OpcNo(0), VTNo(0) {}
380 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
381 /// if the match fails. At this point, we already know that the opcode for N
382 /// matches, and the SDNode for the result has the RootName specified name.
383 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
384 const std::string &RootName, const std::string &ChainSuffix,
387 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
388 const std::string &RootName,
389 const std::string &ChainSuffix, bool &FoundChain);
391 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
392 /// we actually have to build a DAG!
393 std::vector<std::string>
394 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
395 bool InFlagDecled, bool ResNodeDecled,
396 bool LikeLeaf = false, bool isRoot = false);
398 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
399 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
400 /// 'Pat' may be missing types. If we find an unresolved type to add a check
401 /// for, this returns true otherwise false if Pat has all types.
402 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
403 const std::string &Prefix, bool isRoot = false) {
405 if (Pat->getExtTypes() != Other->getExtTypes()) {
406 // Move a type over from 'other' to 'pat'.
407 Pat->setTypes(Other->getExtTypes());
408 // The top level node type is checked outside of the select function.
410 emitCheck(Prefix + ".getValueType() == " +
411 getName(Pat->getTypeNum(0)));
415 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
416 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
417 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
418 Prefix + utostr(OpNo)))
424 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
426 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
427 bool &ChainEmitted, bool &InFlagDecled,
428 bool &ResNodeDecled, bool isRoot = false) {
429 const CodeGenTarget &T = CGP.getTargetInfo();
430 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
431 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
432 TreePatternNode *Child = N->getChild(i);
433 if (!Child->isLeaf()) {
434 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
435 InFlagDecled, ResNodeDecled);
437 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
438 if (!Child->getName().empty()) {
439 std::string Name = RootName + utostr(OpNo);
440 if (Duplicates.find(Name) != Duplicates.end())
441 // A duplicate! Do not emit a copy for this node.
445 Record *RR = DI->getDef();
446 if (RR->isSubClassOf("Register")) {
447 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
448 if (RVT == MVT::Flag) {
450 emitCode("SDValue InFlag = " +
451 getValueName(RootName + utostr(OpNo)) + ";");
454 emitCode("InFlag = " +
455 getValueName(RootName + utostr(OpNo)) + ";");
458 emitCode("SDValue Chain = CurDAG->getEntryNode();");
463 emitCode("SDValue InFlag(0, 0);");
466 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
467 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
468 ", " + getNodeName(RootName) + "->getDebugLoc()" +
469 ", " + getQualifiedName(RR) +
470 ", " + getValueName(RootName + utostr(OpNo)) +
471 ", InFlag).getNode();");
472 ResNodeDecled = true;
473 emitCode(ChainName + " = SDValue(ResNode, 0);");
474 emitCode("InFlag = SDValue(ResNode, 1);");
481 if (N->NodeHasProperty(SDNPInFlag, CGP)) {
483 emitCode("SDValue InFlag = " + getNodeName(RootName) +
484 "->getOperand(" + utostr(OpNo) + ");");
488 emitCode("InFlag = " + getNodeName(RootName) +
489 "->getOperand(" + utostr(OpNo) + ");");
495 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
496 /// if the match fails. At this point, we already know that the opcode for N
497 /// matches, and the SDNode for the result has the RootName specified name.
498 void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
499 const std::string &RootName,
500 const std::string &ChainSuffix,
502 // Save loads/stores matched by a pattern.
503 if (!N->isLeaf() && N->getName().empty()) {
504 if (N->NodeHasProperty(SDNPMemOperand, CGP))
505 LSI.push_back(getNodeName(RootName));
508 bool isRoot = (P == NULL);
509 // Emit instruction predicates. Each predicate is just a string for now.
511 // Record input varargs info.
512 NumInputRootOps = N->getNumChildren();
513 emitCheck(PredicateCheck);
517 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
518 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
519 ")->getSExtValue() == INT64_C(" +
520 itostr(II->getValue()) + ")");
523 assert(N->getComplexPatternInfo(CGP) != 0 &&
524 "Cannot match this as a leaf value!");
527 // If this node has a name associated with it, capture it in VariableMap. If
528 // we already saw this in the pattern, emit code to verify dagness.
529 if (!N->getName().empty()) {
530 std::string &VarMapEntry = VariableMap[N->getName()];
531 if (VarMapEntry.empty()) {
532 VarMapEntry = RootName;
534 // If we get here, this is a second reference to a specific name. Since
535 // we already have checked that the first reference is valid, we don't
536 // have to recursively match it, just check that it's the same as the
537 // previously named thing.
538 emitCheck(VarMapEntry + " == " + RootName);
544 // Emit code to load the child nodes and match their contents recursively.
546 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
547 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
552 // Check if it's profitable to fold the node. e.g. Check for multiple uses
554 std::string ParentName(RootName.begin(), RootName.end()-1);
556 // If this is just an interior node, check to see if it has a single
557 // use. If the node has multiple uses and the pattern has a load as
558 // an operand, then we can't fold the load.
559 emitCheck(getValueName(RootName) + ".hasOneUse()");
560 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
561 // If the immediate use can somehow reach this node through another
562 // path, then can't fold it either or it will create a cycle.
563 // e.g. In the following diagram, XX can reach ld through YY. If
564 // ld is folded into XX, then YY is both a predecessor and a successor
575 // We know we need the check if N's parent is not the root.
576 bool NeedCheck = P != Pattern;
578 // If the parent is the root and the node has more than one operand,
580 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
582 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
583 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
584 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
585 PInfo.getNumOperands() > 1 ||
586 PInfo.hasProperty(SDNPHasChain) ||
587 PInfo.hasProperty(SDNPInFlag) ||
588 PInfo.hasProperty(SDNPOptInFlag);
592 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
593 ", " + getNodeName(ParentName) + ", N)");
594 emitCheck("IsLegalToFold(" + getValueName(RootName) +
595 ", " + getNodeName(ParentName) + ", N)");
597 // Otherwise, just verify that the node only has a single use.
598 emitCheck(getValueName(RootName) + ".hasOneUse()");
605 emitCheck("IsChainCompatible(" + ChainName + ".getNode(), " +
606 getNodeName(RootName) + ")");
607 OrigChains.push_back(std::make_pair(ChainName,
608 getValueName(RootName)));
611 ChainName = "Chain" + ChainSuffix;
613 if (!N->getComplexPatternInfo(CGP) ||
615 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
620 // If there are node predicates for this, emit the calls.
621 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
622 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
624 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
625 // a constant without a predicate fn that has more that one bit set, handle
626 // this as a special case. This is usually for targets that have special
627 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
628 // handling stuff). Using these instructions is often far more efficient
629 // than materializing the constant. Unfortunately, both the instcombiner
630 // and the dag combiner can often infer that bits are dead, and thus drop
631 // them from the mask in the dag. For example, it might turn 'AND X, 255'
632 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
635 (N->getOperator()->getName() == "and" ||
636 N->getOperator()->getName() == "or") &&
637 N->getChild(1)->isLeaf() &&
638 N->getChild(1)->getPredicateFns().empty()) {
639 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
640 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
641 emitInit("SDValue " + RootName + "0" + " = " +
642 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
643 emitInit("SDValue " + RootName + "1" + " = " +
644 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
646 unsigned NTmp = TmpNo++;
647 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
648 " = dyn_cast<ConstantSDNode>(" +
649 getNodeName(RootName + "1") + ");");
650 emitCheck("Tmp" + utostr(NTmp));
651 const char *MaskPredicate = N->getOperator()->getName() == "or"
652 ? "CheckOrMask(" : "CheckAndMask(";
653 emitCheck(MaskPredicate + getValueName(RootName + "0") +
654 ", Tmp" + utostr(NTmp) +
655 ", INT64_C(" + itostr(II->getValue()) + "))");
657 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
658 ChainSuffix + utostr(0), FoundChain);
664 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
665 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
666 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
668 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
669 ChainSuffix + utostr(OpNo), FoundChain);
672 // Handle complex patterns.
673 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
674 std::string Fn = CP->getSelectFunc();
675 unsigned NumOps = CP->getNumOperands();
676 for (unsigned i = 0; i < NumOps; ++i) {
677 emitDecl("CPTmp" + RootName + "_" + utostr(i));
678 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
680 if (CP->hasProperty(SDNPHasChain)) {
681 emitDecl("CPInChain");
682 emitDecl("Chain" + ChainSuffix);
683 emitCode("SDValue CPInChain;");
684 emitCode("SDValue Chain" + ChainSuffix + ";");
687 std::string Code = Fn + "(N, "; // always pass in the root.
688 Code += getValueName(RootName);
689 for (unsigned i = 0; i < NumOps; i++)
690 Code += ", CPTmp" + RootName + "_" + utostr(i);
691 if (CP->hasProperty(SDNPHasChain)) {
692 ChainName = "Chain" + ChainSuffix;
693 Code += ", CPInChain, " + ChainName;
695 emitCheck(Code + ")");
699 void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
700 TreePatternNode *Parent,
701 const std::string &RootName,
702 const std::string &ChainSuffix,
704 if (!Child->isLeaf()) {
705 // If it's not a leaf, recursively match.
706 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
707 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
708 CInfo.getEnumName());
709 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
710 bool HasChain = false;
711 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
713 FoldedChains.push_back(std::make_pair(getValueName(RootName),
714 CInfo.getNumResults()));
716 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
717 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
718 "Pattern folded multiple nodes which produce flags?");
719 FoldedFlag = std::make_pair(getValueName(RootName),
720 CInfo.getNumResults() + (unsigned)HasChain);
725 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
726 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
727 bool HasChain = false;
729 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
731 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
732 FoldedChains.push_back(std::make_pair("CPInChain",
733 PInfo.getNumResults()));
735 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
736 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
737 "Pattern folded multiple nodes which produce flags?");
738 FoldedFlag = std::make_pair(getValueName(RootName),
739 CP->getNumOperands() + (unsigned)HasChain);
744 // If this child has a name associated with it, capture it in VarMap. If
745 // we already saw this in the pattern, emit code to verify dagness.
746 if (!Child->getName().empty()) {
747 std::string &VarMapEntry = VariableMap[Child->getName()];
748 if (VarMapEntry.empty()) {
749 VarMapEntry = getValueName(RootName);
751 // If we get here, this is a second reference to a specific name.
752 // Since we already have checked that the first reference is valid,
753 // we don't have to recursively match it, just check that it's the
754 // same as the previously named thing.
755 emitCheck(VarMapEntry + " == " + getValueName(RootName));
756 Duplicates.insert(getValueName(RootName));
761 // Handle leaves of various types.
762 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
763 Record *LeafRec = DI->getDef();
764 if (LeafRec->isSubClassOf("RegisterClass") ||
765 LeafRec->isSubClassOf("PointerLikeRegClass")) {
766 // Handle register references. Nothing to do here.
767 } else if (LeafRec->isSubClassOf("Register")) {
768 // Handle register references.
769 } else if (LeafRec->getName() == "srcvalue") {
770 // Place holder for SRCVALUE nodes. Nothing to do here.
771 } else if (LeafRec->isSubClassOf("ValueType")) {
772 // Make sure this is the specified value type.
773 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
774 ")->getVT() == MVT::" + LeafRec->getName());
775 } else if (LeafRec->isSubClassOf("CondCode")) {
776 // Make sure this is the specified cond code.
777 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
778 ")->get() == ISD::" + LeafRec->getName());
784 assert(0 && "Unknown leaf type!");
787 // If there are node predicates for this, emit the calls.
788 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
789 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
794 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
795 unsigned NTmp = TmpNo++;
796 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
797 " = dyn_cast<ConstantSDNode>("+
798 getNodeName(RootName) + ");");
799 emitCheck("Tmp" + utostr(NTmp));
800 unsigned CTmp = TmpNo++;
801 emitCode("int64_t CN"+ utostr(CTmp) +
802 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
803 emitCheck("CN" + utostr(CTmp) + " == "
804 "INT64_C(" +itostr(II->getValue()) + ")");
810 assert(0 && "Unknown leaf type!");
813 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
814 /// we actually have to build a DAG!
815 std::vector<std::string>
816 PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
817 std::vector<Record*> DstRegs,
818 bool InFlagDecled, bool ResNodeDecled,
819 bool LikeLeaf, bool isRoot) {
820 // List of arguments of getMachineNode() or SelectNodeTo().
821 std::vector<std::string> NodeOps;
822 // This is something selected from the pattern we matched.
823 if (!N->getName().empty()) {
824 const std::string &VarName = N->getName();
825 std::string Val = VariableMap[VarName];
827 errs() << "Variable '" << VarName << " referenced but not defined "
828 << "and not caught earlier!\n";
832 unsigned ResNo = TmpNo++;
833 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
834 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
835 std::string CastType;
836 std::string TmpVar = "Tmp" + utostr(ResNo);
837 switch (N->getTypeNum(0)) {
839 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
840 << " type as an immediate constant. Aborting\n";
842 case MVT::i1: CastType = "bool"; break;
843 case MVT::i8: CastType = "unsigned char"; break;
844 case MVT::i16: CastType = "unsigned short"; break;
845 case MVT::i32: CastType = "unsigned"; break;
846 case MVT::i64: CastType = "uint64_t"; break;
848 emitCode("SDValue " + TmpVar +
849 " = CurDAG->getTargetConstant(((" + CastType +
850 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
851 getEnumName(N->getTypeNum(0)) + ");");
852 NodeOps.push_back(getValueName(TmpVar));
853 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
854 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
855 std::string TmpVar = "Tmp" + utostr(ResNo);
856 emitCode("SDValue " + TmpVar +
857 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
858 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
859 Val + ")->getValueType(0));");
860 NodeOps.push_back(getValueName(TmpVar));
861 } else if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
862 for (unsigned i = 0; i < CP->getNumOperands(); ++i)
863 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
865 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
866 // node even if it isn't one. Don't select it.
868 if (isRoot && N->isLeaf()) {
869 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
870 emitCode("return NULL;");
873 NodeOps.push_back(getValueName(Val));
878 // If this is an explicit register reference, handle it.
879 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
880 unsigned ResNo = TmpNo++;
881 if (DI->getDef()->isSubClassOf("Register")) {
882 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
883 getQualifiedName(DI->getDef()) + ", " +
884 getEnumName(N->getTypeNum(0)) + ");");
885 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
887 } else if (DI->getDef()->getName() == "zero_reg") {
888 emitCode("SDValue Tmp" + utostr(ResNo) +
889 " = CurDAG->getRegister(0, " +
890 getEnumName(N->getTypeNum(0)) + ");");
891 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
893 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
894 // Handle a reference to a register class. This is used
895 // in COPY_TO_SUBREG instructions.
896 emitCode("SDValue Tmp" + utostr(ResNo) +
897 " = CurDAG->getTargetConstant(" +
898 getQualifiedName(DI->getDef()) + "RegClassID, " +
900 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
903 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
904 unsigned ResNo = TmpNo++;
905 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
906 emitCode("SDValue Tmp" + utostr(ResNo) +
907 " = CurDAG->getTargetConstant(0x" +
908 utohexstr((uint64_t) II->getValue()) +
909 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
910 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
917 assert(0 && "Unknown leaf type!");
921 Record *Op = N->getOperator();
922 if (Op->isSubClassOf("Instruction")) {
923 const CodeGenTarget &CGT = CGP.getTargetInfo();
924 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
925 const DAGInstruction &Inst = CGP.getInstruction(Op);
926 const TreePattern *InstPat = Inst.getPattern();
927 // FIXME: Assume actual pattern comes before "implicit".
928 TreePatternNode *InstPatNode =
929 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
930 : (InstPat ? InstPat->getTree(0) : NULL);
931 if (InstPatNode && !InstPatNode->isLeaf() &&
932 InstPatNode->getOperator()->getName() == "set") {
933 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
935 bool IsVariadic = isRoot && II.isVariadic;
936 // FIXME: fix how we deal with physical register operands.
937 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
938 bool HasImpResults = isRoot && DstRegs.size() > 0;
939 bool NodeHasOptInFlag = isRoot &&
940 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
941 bool NodeHasInFlag = isRoot &&
942 Pattern->TreeHasProperty(SDNPInFlag, CGP);
943 bool NodeHasOutFlag = isRoot &&
944 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
945 bool NodeHasChain = InstPatNode &&
946 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
947 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
948 unsigned NumResults = Inst.getNumResults();
949 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
951 // Record output varargs info.
952 OutputIsVariadic = IsVariadic;
954 if (NodeHasOptInFlag) {
955 emitCode("bool HasInFlag = "
956 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
960 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
962 // How many results is this pattern expected to produce?
963 unsigned NumPatResults = 0;
964 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
965 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
966 if (VT != MVT::isVoid && VT != MVT::Flag)
970 if (OrigChains.size() > 0) {
971 // The original input chain is being ignored. If it is not just
972 // pointing to the op that's being folded, we should create a
973 // TokenFactor with it and the chain of the folded op as the new chain.
974 // We could potentially be doing multiple levels of folding, in that
975 // case, the TokenFactor can have more operands.
976 emitCode("SmallVector<SDValue, 8> InChains;");
977 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
978 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
979 OrigChains[i].second + ".getNode()) {");
980 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
983 emitCode("InChains.push_back(" + ChainName + ");");
984 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
985 "N->getDebugLoc(), MVT::Other, "
986 "&InChains[0], InChains.size());");
988 emitCode("CurDAG->setSubgraphColor(" + ChainName +
989 ".getNode(), \"yellow\");");
990 emitCode("CurDAG->setSubgraphColor(" + ChainName +
991 ".getNode(), \"black\");");
995 // Loop over all of the operands of the instruction pattern, emitting code
996 // to fill them all in. The node 'N' usually has number children equal to
997 // the number of input operands of the instruction. However, in cases
998 // where there are predicate operands for an instruction, we need to fill
999 // in the 'execute always' values. Match up the node operands to the
1000 // instruction operands to do this.
1001 std::vector<std::string> AllOps;
1002 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1003 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1004 std::vector<std::string> Ops;
1006 // Determine what to emit for this operand.
1007 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1008 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1009 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1010 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1011 // This is a predicate or optional def operand; emit the
1012 // 'default ops' operands.
1013 const DAGDefaultOperand &DefaultOp =
1014 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1015 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1016 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1017 InFlagDecled, ResNodeDecled);
1018 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1021 // Otherwise this is a normal operand or a predicate operand without
1022 // 'execute always'; emit it.
1023 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1024 InFlagDecled, ResNodeDecled);
1025 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1030 // Emit all the chain and CopyToReg stuff.
1031 bool ChainEmitted = NodeHasChain;
1032 if (NodeHasInFlag || HasImpInputs)
1033 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1034 InFlagDecled, ResNodeDecled, true);
1035 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1036 if (!InFlagDecled) {
1037 emitCode("SDValue InFlag(0, 0);");
1038 InFlagDecled = true;
1040 if (NodeHasOptInFlag) {
1041 emitCode("if (HasInFlag) {");
1042 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1047 unsigned ResNo = TmpNo++;
1049 unsigned OpsNo = OpcNo;
1050 std::string CodePrefix;
1051 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1052 std::deque<std::string> After;
1053 std::string NodeName;
1055 NodeName = "Tmp" + utostr(ResNo);
1056 CodePrefix = "SDValue " + NodeName + "(";
1058 NodeName = "ResNode";
1059 if (!ResNodeDecled) {
1060 CodePrefix = "SDNode *" + NodeName + " = ";
1061 ResNodeDecled = true;
1063 CodePrefix = NodeName + " = ";
1066 std::string Code = "Opc" + utostr(OpcNo);
1068 if (!isRoot || (InputHasChain && !NodeHasChain))
1069 // For call to "getMachineNode()".
1070 Code += ", N->getDebugLoc()";
1072 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1074 // Output order: results, chain, flags
1076 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1077 Code += ", VT" + utostr(VTNo);
1078 emitVT(getEnumName(N->getTypeNum(0)));
1080 // Add types for implicit results in physical registers, scheduler will
1081 // care of adding copyfromreg nodes.
1082 for (unsigned i = 0; i < NumDstRegs; i++) {
1083 Record *RR = DstRegs[i];
1084 if (RR->isSubClassOf("Register")) {
1085 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1086 Code += ", " + getEnumName(RVT);
1090 Code += ", MVT::Other";
1092 Code += ", MVT::Flag";
1096 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1097 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1100 // Figure out whether any operands at the end of the op list are not
1101 // part of the variable section.
1102 std::string EndAdjust;
1103 if (NodeHasInFlag || HasImpInputs)
1104 EndAdjust = "-1"; // Always has one flag.
1105 else if (NodeHasOptInFlag)
1106 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1108 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1109 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1111 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1115 // Populate MemRefs with entries for each memory accesses covered by
1117 if (isRoot && !LSI.empty()) {
1118 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1119 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1120 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1121 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1122 emitCode(MemRefs + "[" + utostr(i) + "] = "
1123 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1124 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1125 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1131 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1133 AllOps.push_back(ChainName);
1137 if (NodeHasInFlag || HasImpInputs)
1138 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1139 else if (NodeHasOptInFlag) {
1140 emitCode("if (HasInFlag)");
1141 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1143 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1145 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1146 AllOps.push_back("InFlag");
1148 unsigned NumOps = AllOps.size();
1150 if (!NodeHasOptInFlag && NumOps < 4) {
1151 for (unsigned i = 0; i != NumOps; ++i)
1152 Code += ", " + AllOps[i];
1154 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1155 for (unsigned i = 0; i != NumOps; ++i) {
1156 OpsCode += AllOps[i];
1160 emitCode(OpsCode + " };");
1161 Code += ", Ops" + utostr(OpsNo) + ", ";
1162 if (NodeHasOptInFlag) {
1163 Code += "HasInFlag ? ";
1164 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1166 Code += utostr(NumOps);
1173 std::vector<std::string> ReplaceFroms;
1174 std::vector<std::string> ReplaceTos;
1176 NodeOps.push_back("Tmp" + utostr(ResNo));
1179 if (NodeHasOutFlag) {
1180 if (!InFlagDecled) {
1181 After.push_back("SDValue InFlag(ResNode, " +
1182 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1184 InFlagDecled = true;
1186 After.push_back("InFlag = SDValue(ResNode, " +
1187 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1191 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1192 ReplaceFroms.push_back("SDValue(" +
1193 FoldedChains[j].first + ".getNode(), " +
1194 utostr(FoldedChains[j].second) +
1196 ReplaceTos.push_back("SDValue(ResNode, " +
1197 utostr(NumResults+NumDstRegs) + ")");
1200 if (NodeHasOutFlag) {
1201 if (FoldedFlag.first != "") {
1202 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1203 utostr(FoldedFlag.second) + ")");
1204 ReplaceTos.push_back("InFlag");
1206 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
1207 ReplaceFroms.push_back("SDValue(N, " +
1208 utostr(NumPatResults + (unsigned)InputHasChain)
1210 ReplaceTos.push_back("InFlag");
1214 if (!ReplaceFroms.empty() && InputHasChain) {
1215 ReplaceFroms.push_back("SDValue(N, " +
1216 utostr(NumPatResults) + ")");
1217 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1218 ChainName + ".getResNo()" + ")");
1219 ChainAssignmentNeeded |= NodeHasChain;
1222 // User does not expect the instruction would produce a chain!
1223 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1225 } else if (InputHasChain && !NodeHasChain) {
1226 // One of the inner node produces a chain.
1227 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1228 ReplaceFroms.push_back("SDValue(N, " +
1229 utostr(NumPatResults) + ")");
1230 ReplaceTos.push_back(ChainName);
1234 if (ChainAssignmentNeeded) {
1235 // Remember which op produces the chain.
1236 std::string ChainAssign;
1238 ChainAssign = ChainName + " = SDValue(" + NodeName +
1239 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1241 ChainAssign = ChainName + " = SDValue(" + NodeName +
1242 ", " + utostr(NumResults+NumDstRegs) + ");";
1244 After.push_front(ChainAssign);
1247 if (ReplaceFroms.size() == 1) {
1248 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1249 ReplaceTos[0] + ");");
1250 } else if (!ReplaceFroms.empty()) {
1251 After.push_back("const SDValue Froms[] = {");
1252 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1253 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1254 After.push_back("};");
1255 After.push_back("const SDValue Tos[] = {");
1256 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1257 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1258 After.push_back("};");
1259 After.push_back("ReplaceUses(Froms, Tos, " +
1260 itostr(ReplaceFroms.size()) + ");");
1263 // We prefer to use SelectNodeTo since it avoids allocation when
1264 // possible and it avoids CSE map recalculation for the node's
1265 // users, however it's tricky to use in a non-root context.
1267 // We also don't use SelectNodeTo if the pattern replacement is being
1268 // used to jettison a chain result, since morphing the node in place
1269 // would leave users of the chain dangling.
1271 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1272 Code = "CurDAG->getMachineNode(" + Code;
1274 Code = "CurDAG->SelectNodeTo(N, " + Code;
1278 CodePrefix = "return ";
1280 After.push_back("return ResNode;");
1283 emitCode(CodePrefix + Code + ");");
1287 emitCode("CurDAG->setSubgraphColor(" +
1288 NodeName +".getNode(), \"yellow\");");
1289 emitCode("CurDAG->setSubgraphColor(" +
1290 NodeName +".getNode(), \"black\");");
1292 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1293 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1297 for (unsigned i = 0, e = After.size(); i != e; ++i)
1302 if (Op->isSubClassOf("SDNodeXForm")) {
1303 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1304 // PatLeaf node - the operand may or may not be a leaf node. But it should
1306 std::vector<std::string> Ops =
1307 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1308 ResNodeDecled, true);
1309 unsigned ResNo = TmpNo++;
1310 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1311 + "(" + Ops.back() + ".getNode());");
1312 NodeOps.push_back("Tmp" + utostr(ResNo));
1314 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1320 throw std::string("Unknown node in result pattern!");
1324 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1325 /// stream to match the pattern, and generate the code for the match if it
1326 /// succeeds. Returns true if the pattern is not guaranteed to match.
1327 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1328 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1329 std::set<std::string> &GeneratedDecl,
1330 std::vector<std::string> &TargetOpcodes,
1331 std::vector<std::string> &TargetVTs,
1332 bool &OutputIsVariadic,
1333 unsigned &NumInputRootOps) {
1334 OutputIsVariadic = false;
1335 NumInputRootOps = 0;
1337 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1338 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1339 GeneratedCode, GeneratedDecl,
1340 TargetOpcodes, TargetVTs,
1341 OutputIsVariadic, NumInputRootOps);
1343 // Emit the matcher, capturing named arguments in VariableMap.
1344 bool FoundChain = false;
1345 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1347 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1348 // diagnostics, which we know are impossible at this point.
1349 TreePattern &TP = *CGP.pf_begin()->second;
1351 // At this point, we know that we structurally match the pattern, but the
1352 // types of the nodes may not match. Figure out the fewest number of type
1353 // comparisons we need to emit. For example, if there is only one integer
1354 // type supported by a target, there should be no type comparisons at all for
1355 // integer patterns!
1357 // To figure out the fewest number of type checks needed, clone the pattern,
1358 // remove the types, then perform type inference on the pattern as a whole.
1359 // If there are unresolved types, emit an explicit check for those types,
1360 // apply the type to the tree, then rerun type inference. Iterate until all
1361 // types are resolved.
1363 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1364 Pat->RemoveAllTypes();
1367 // Resolve/propagate as many types as possible.
1369 bool MadeChange = true;
1371 MadeChange = Pat->ApplyTypeConstraints(TP,
1372 true/*Ignore reg constraints*/);
1374 assert(0 && "Error: could not find consistent types for something we"
1375 " already decided was ok!");
1379 // Insert a check for an unresolved type and add it to the tree. If we find
1380 // an unresolved type to add a check for, this returns true and we iterate,
1381 // otherwise we are done.
1382 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1384 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1385 false, false, false, true);
1389 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1390 /// a line causes any of them to be empty, remove them and return true when
1392 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1393 std::vector<std::pair<unsigned, std::string> > > >
1395 bool ErasedPatterns = false;
1396 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1397 Patterns[i].second.pop_back();
1398 if (Patterns[i].second.empty()) {
1399 Patterns.erase(Patterns.begin()+i);
1401 ErasedPatterns = true;
1404 return ErasedPatterns;
1407 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1408 /// code together between the patterns.
1409 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1410 std::vector<std::pair<unsigned, std::string> > > >
1411 &Patterns, unsigned Indent,
1413 typedef std::pair<unsigned, std::string> CodeLine;
1414 typedef std::vector<CodeLine> CodeList;
1415 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1417 if (Patterns.empty()) return;
1419 // Figure out how many patterns share the next code line. Explicitly copy
1420 // FirstCodeLine so that we don't invalidate a reference when changing
1422 const CodeLine FirstCodeLine = Patterns.back().second.back();
1423 unsigned LastMatch = Patterns.size()-1;
1424 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1427 // If not all patterns share this line, split the list into two pieces. The
1428 // first chunk will use this line, the second chunk won't.
1429 if (LastMatch != 0) {
1430 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1431 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1433 // FIXME: Emit braces?
1434 if (Shared.size() == 1) {
1435 const PatternToMatch &Pattern = *Shared.back().first;
1436 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1437 Pattern.getSrcPattern()->print(OS);
1438 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1439 Pattern.getDstPattern()->print(OS);
1441 unsigned AddedComplexity = Pattern.getAddedComplexity();
1442 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1443 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1445 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1447 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1449 if (FirstCodeLine.first != 1) {
1450 OS << std::string(Indent, ' ') << "{\n";
1453 EmitPatterns(Shared, Indent, OS);
1454 if (FirstCodeLine.first != 1) {
1456 OS << std::string(Indent, ' ') << "}\n";
1459 if (Other.size() == 1) {
1460 const PatternToMatch &Pattern = *Other.back().first;
1461 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1462 Pattern.getSrcPattern()->print(OS);
1463 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1464 Pattern.getDstPattern()->print(OS);
1466 unsigned AddedComplexity = Pattern.getAddedComplexity();
1467 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1468 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1470 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1472 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1474 EmitPatterns(Other, Indent, OS);
1478 // Remove this code from all of the patterns that share it.
1479 bool ErasedPatterns = EraseCodeLine(Patterns);
1481 bool isPredicate = FirstCodeLine.first == 1;
1483 // Otherwise, every pattern in the list has this line. Emit it.
1486 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1488 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1490 // If the next code line is another predicate, and if all of the pattern
1491 // in this group share the same next line, emit it inline now. Do this
1492 // until we run out of common predicates.
1493 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1494 // Check that all of the patterns in Patterns end with the same predicate.
1495 bool AllEndWithSamePredicate = true;
1496 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1497 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1498 AllEndWithSamePredicate = false;
1501 // If all of the predicates aren't the same, we can't share them.
1502 if (!AllEndWithSamePredicate) break;
1504 // Otherwise we can. Emit it shared now.
1505 OS << " &&\n" << std::string(Indent+4, ' ')
1506 << Patterns.back().second.back().second;
1507 ErasedPatterns = EraseCodeLine(Patterns);
1514 EmitPatterns(Patterns, Indent, OS);
1517 OS << std::string(Indent-2, ' ') << "}\n";
1520 static std::string getLegalCName(std::string OpName) {
1521 std::string::size_type pos = OpName.find("::");
1522 if (pos != std::string::npos)
1523 OpName.replace(pos, 2, "_");
1527 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1528 const CodeGenTarget &Target = CGP.getTargetInfo();
1530 // Get the namespace to insert instructions into.
1531 std::string InstNS = Target.getInstNamespace();
1532 if (!InstNS.empty()) InstNS += "::";
1534 // Group the patterns by their top-level opcodes.
1535 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1536 // All unique target node emission functions.
1537 std::map<std::string, unsigned> EmitFunctions;
1538 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1539 E = CGP.ptm_end(); I != E; ++I) {
1540 const PatternToMatch &Pattern = *I;
1541 TreePatternNode *Node = Pattern.getSrcPattern();
1542 if (!Node->isLeaf()) {
1543 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1544 push_back(&Pattern);
1546 const ComplexPattern *CP;
1547 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1548 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1549 push_back(&Pattern);
1550 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
1551 std::vector<Record*> OpNodes = CP->getRootNodes();
1552 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1553 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1554 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1558 errs() << "Unrecognized opcode '";
1560 errs() << "' on tree pattern '";
1561 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1567 // For each opcode, there might be multiple select functions, one per
1568 // ValueType of the node (or its first operand if it doesn't produce a
1569 // non-chain result.
1570 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1572 // Emit one Select_* method for each top-level opcode. We do this instead of
1573 // emitting one giant switch statement to support compilers where this will
1574 // result in the recursive functions taking less stack space.
1575 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1576 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1577 PBOI != E; ++PBOI) {
1578 const std::string &OpName = PBOI->first;
1579 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1580 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1582 // Split them into groups by type.
1583 std::map<MVT::SimpleValueType,
1584 std::vector<const PatternToMatch*> > PatternsByType;
1585 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1586 const PatternToMatch *Pat = PatternsOfOp[i];
1587 TreePatternNode *SrcPat = Pat->getSrcPattern();
1588 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1591 for (std::map<MVT::SimpleValueType,
1592 std::vector<const PatternToMatch*> >::iterator
1593 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1595 MVT::SimpleValueType OpVT = II->first;
1596 std::vector<const PatternToMatch*> &Patterns = II->second;
1597 typedef std::pair<unsigned, std::string> CodeLine;
1598 typedef std::vector<CodeLine> CodeList;
1599 typedef CodeList::iterator CodeListI;
1601 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1602 std::vector<std::vector<std::string> > PatternOpcodes;
1603 std::vector<std::vector<std::string> > PatternVTs;
1604 std::vector<std::set<std::string> > PatternDecls;
1605 std::vector<bool> OutputIsVariadicFlags;
1606 std::vector<unsigned> NumInputRootOpsCounts;
1607 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1608 CodeList GeneratedCode;
1609 std::set<std::string> GeneratedDecl;
1610 std::vector<std::string> TargetOpcodes;
1611 std::vector<std::string> TargetVTs;
1612 bool OutputIsVariadic;
1613 unsigned NumInputRootOps;
1614 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1615 TargetOpcodes, TargetVTs,
1616 OutputIsVariadic, NumInputRootOps);
1617 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1618 PatternDecls.push_back(GeneratedDecl);
1619 PatternOpcodes.push_back(TargetOpcodes);
1620 PatternVTs.push_back(TargetVTs);
1621 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1622 NumInputRootOpsCounts.push_back(NumInputRootOps);
1625 // Factor target node emission code (emitted by EmitResultCode) into
1626 // separate functions. Uniquing and share them among all instruction
1627 // selection routines.
1628 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1629 CodeList &GeneratedCode = CodeForPatterns[i].second;
1630 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1631 std::vector<std::string> &TargetVTs = PatternVTs[i];
1632 std::set<std::string> Decls = PatternDecls[i];
1633 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1634 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1635 std::vector<std::string> AddedInits;
1636 int CodeSize = (int)GeneratedCode.size();
1638 for (int j = CodeSize-1; j >= 0; --j) {
1639 if (LastPred == -1 && GeneratedCode[j].first == 1)
1641 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1642 AddedInits.push_back(GeneratedCode[j].second);
1645 std::string CalleeCode = "(SDNode *N";
1646 std::string CallerCode = "(N";
1647 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1648 CalleeCode += ", unsigned Opc" + utostr(j);
1649 CallerCode += ", " + TargetOpcodes[j];
1651 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1652 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1653 CallerCode += ", " + TargetVTs[j];
1655 for (std::set<std::string>::iterator
1656 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1657 std::string Name = *I;
1658 CalleeCode += ", SDValue &" + Name;
1659 CallerCode += ", " + Name;
1662 if (OutputIsVariadic) {
1663 CalleeCode += ", unsigned NumInputRootOps";
1664 CallerCode += ", " + utostr(NumInputRootOps);
1668 CalleeCode += ") {\n";
1670 for (std::vector<std::string>::const_reverse_iterator
1671 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1672 CalleeCode += " " + *I + "\n";
1674 for (int j = LastPred+1; j < CodeSize; ++j)
1675 CalleeCode += " " + GeneratedCode[j].second + "\n";
1676 for (int j = LastPred+1; j < CodeSize; ++j)
1677 GeneratedCode.pop_back();
1678 CalleeCode += "}\n";
1680 // Uniquing the emission routines.
1681 unsigned EmitFuncNum;
1682 std::map<std::string, unsigned>::iterator EFI =
1683 EmitFunctions.find(CalleeCode);
1684 if (EFI != EmitFunctions.end()) {
1685 EmitFuncNum = EFI->second;
1687 EmitFuncNum = EmitFunctions.size();
1688 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1689 // Prevent emission routines from being inlined to reduce selection
1690 // routines stack frame sizes.
1691 OS << "DISABLE_INLINE ";
1692 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1695 // Replace the emission code within selection routines with calls to the
1696 // emission functions.
1698 GeneratedCode.push_back(std::make_pair(0,
1699 "CurDAG->setSubgraphColor(N, \"red\");"));
1700 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) +CallerCode;
1701 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1703 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1704 GeneratedCode.push_back(std::make_pair(0,
1705 " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1706 GeneratedCode.push_back(std::make_pair(0,
1707 " CurDAG->setSubgraphColor(Result, \"black\");"));
1708 GeneratedCode.push_back(std::make_pair(0, "}"));
1710 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1714 std::string OpVTStr;
1715 if (OpVT == MVT::iPTR) {
1717 } else if (OpVT == MVT::iPTRAny) {
1718 OpVTStr = "_iPTRAny";
1719 } else if (OpVT == MVT::isVoid) {
1720 // Nodes with a void result actually have a first result type of either
1721 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1722 // void to this case, we handle it specially here.
1724 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1726 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1727 OpcodeVTMap.find(OpName);
1728 if (OpVTI == OpcodeVTMap.end()) {
1729 std::vector<std::string> VTSet;
1730 VTSet.push_back(OpVTStr);
1731 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1733 OpVTI->second.push_back(OpVTStr);
1735 // We want to emit all of the matching code now. However, we want to emit
1736 // the matches in order of minimal cost. Sort the patterns so the least
1737 // cost one is at the start.
1738 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1739 PatternSortingPredicate(CGP));
1741 // Scan the code to see if all of the patterns are reachable and if it is
1742 // possible that the last one might not match.
1743 bool mightNotMatch = true;
1744 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1745 CodeList &GeneratedCode = CodeForPatterns[i].second;
1746 mightNotMatch = false;
1748 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1749 if (GeneratedCode[j].first == 1) { // predicate.
1750 mightNotMatch = true;
1755 // If this pattern definitely matches, and if it isn't the last one, the
1756 // patterns after it CANNOT ever match. Error out.
1757 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1758 errs() << "Pattern '";
1759 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1760 errs() << "' is impossible to select!\n";
1765 // Loop through and reverse all of the CodeList vectors, as we will be
1766 // accessing them from their logical front, but accessing the end of a
1767 // vector is more efficient.
1768 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1769 CodeList &GeneratedCode = CodeForPatterns[i].second;
1770 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1773 // Next, reverse the list of patterns itself for the same reason.
1774 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1776 OS << "SDNode *Select_" << getLegalCName(OpName)
1777 << OpVTStr << "(SDNode *N) {\n";
1779 // Emit all of the patterns now, grouped together to share code.
1780 EmitPatterns(CodeForPatterns, 2, OS);
1782 // If the last pattern has predicates (which could fail) emit code to
1783 // catch the case where nothing handles a pattern.
1784 if (mightNotMatch) {
1786 OS << " CannotYetSelect(N);\n";
1787 OS << " return NULL;\n";
1793 OS << "// The main instruction selector code.\n"
1794 << "SDNode *SelectCode(SDNode *N) {\n"
1795 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1796 << " switch (N->getOpcode()) {\n"
1798 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
1800 << " case ISD::EntryToken: // These nodes remain the same.\n"
1801 << " case ISD::BasicBlock:\n"
1802 << " case ISD::Register:\n"
1803 << " case ISD::HANDLENODE:\n"
1804 << " case ISD::TargetConstant:\n"
1805 << " case ISD::TargetConstantFP:\n"
1806 << " case ISD::TargetConstantPool:\n"
1807 << " case ISD::TargetFrameIndex:\n"
1808 << " case ISD::TargetExternalSymbol:\n"
1809 << " case ISD::TargetBlockAddress:\n"
1810 << " case ISD::TargetJumpTable:\n"
1811 << " case ISD::TargetGlobalTLSAddress:\n"
1812 << " case ISD::TargetGlobalAddress:\n"
1813 << " case ISD::TokenFactor:\n"
1814 << " case ISD::CopyFromReg:\n"
1815 << " case ISD::CopyToReg: {\n"
1816 << " return NULL;\n"
1818 << " case ISD::AssertSext:\n"
1819 << " case ISD::AssertZext: {\n"
1820 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
1821 << " return NULL;\n"
1823 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1824 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1825 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1827 // Loop over all of the case statements, emiting a call to each method we
1829 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1830 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1831 PBOI != E; ++PBOI) {
1832 const std::string &OpName = PBOI->first;
1833 // Potentially multiple versions of select for this opcode. One for each
1834 // ValueType of the node (or its first true operand if it doesn't produce a
1836 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1837 OpcodeVTMap.find(OpName);
1838 std::vector<std::string> &OpVTs = OpVTI->second;
1839 OS << " case " << OpName << ": {\n";
1840 // If we have only one variant and it's the default, elide the
1841 // switch. Marginally faster, and makes MSVC happier.
1842 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1843 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1848 // Keep track of whether we see a pattern that has an iPtr result.
1849 bool HasPtrPattern = false;
1850 bool HasDefaultPattern = false;
1852 OS << " switch (NVT) {\n";
1853 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1854 std::string &VTStr = OpVTs[i];
1855 if (VTStr.empty()) {
1856 HasDefaultPattern = true;
1860 // If this is a match on iPTR: don't emit it directly, we need special
1862 if (VTStr == "_iPTR") {
1863 HasPtrPattern = true;
1866 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1867 << " return Select_" << getLegalCName(OpName)
1868 << VTStr << "(N);\n";
1870 OS << " default:\n";
1872 // If there is an iPTR result version of this pattern, emit it here.
1873 if (HasPtrPattern) {
1874 OS << " if (TLI.getPointerTy() == NVT)\n";
1875 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1877 if (HasDefaultPattern) {
1878 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1886 OS << " } // end of big switch.\n\n"
1887 << " CannotYetSelect(N);\n"
1888 << " return NULL;\n"
1892 void DAGISelEmitter::run(raw_ostream &OS) {
1893 EmitSourceFileHeader("DAG Instruction Selector for the " +
1894 CGP.getTargetInfo().getName() + " target", OS);
1896 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1897 << "// *** instruction selector class. These functions are really "
1900 OS << "// Include standard, target-independent definitions and methods used\n"
1901 << "// by the instruction selector.\n";
1902 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
1904 EmitNodeTransforms(OS);
1905 EmitPredicateFunctions(OS);
1907 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
1908 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1910 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1911 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1912 DEBUG(errs() << "\n");
1915 // At this point, we have full information about the 'Patterns' we need to
1916 // parse, both implicitly from instructions as well as from explicit pattern
1917 // definitions. Emit the resultant instruction selector.
1918 EmitInstructionSelector(OS);
1921 MatcherNode *Matcher = 0;
1922 // Walk the patterns backwards, building a matcher for each and adding it to
1923 // the matcher for the whole target.
1924 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1925 E = CGP.ptm_end(); I != E;) {
1926 const PatternToMatch &Pattern = *--E;
1927 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
1932 Matcher = new PushMatcherNode(N, Matcher);
1935 // OptimizeMatcher(Matcher);
1936 EmitMatcherTable(Matcher, OS);