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, const CodeGenTarget &T) {
173 bool FoundRC = false;
174 MVT::SimpleValueType VT = MVT::Other;
175 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
176 std::vector<CodeGenRegisterClass>::const_iterator RC;
177 std::vector<Record*>::const_iterator Element;
179 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
180 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
181 if (Element != (*RC).Elements.end()) {
184 VT = (*RC).getValueTypeNum(0);
187 if (VT != (*RC).getValueTypeNum(0)) {
188 // Types of the RC's do not agree. Return MVT::Other. The
189 // target is responsible for handling this.
198 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
199 return CGP.getSDNodeInfo(Op).getEnumName();
202 //===----------------------------------------------------------------------===//
203 // Node Transformation emitter implementation.
205 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
206 // Walk the pattern fragments, adding them to a map, which sorts them by
208 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
209 NXsByNameTy NXsByName;
211 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
213 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
215 OS << "\n// Node transformations.\n";
217 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
219 Record *SDNode = I->second.first;
220 std::string Code = I->second.second;
222 if (Code.empty()) continue; // Empty code? Skip it.
224 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
225 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
227 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
229 if (ClassName != "SDNode")
230 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
231 OS << Code << "\n}\n";
235 //===----------------------------------------------------------------------===//
236 // Predicate emitter implementation.
239 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
240 OS << "\n// Predicate functions.\n";
242 // Walk the pattern fragments, adding them to a map, which sorts them by
244 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
245 PFsByNameTy PFsByName;
247 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
249 PFsByName.insert(std::make_pair(I->first->getName(), *I));
252 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
254 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
255 TreePattern *P = I->second.second;
257 // If there is a code init for this fragment, emit the predicate code.
258 std::string Code = PatFragRecord->getValueAsCode("Predicate");
259 if (Code.empty()) continue;
261 if (P->getOnlyTree()->isLeaf())
262 OS << "inline bool Predicate_" << PatFragRecord->getName()
263 << "(SDNode *N) const {\n";
265 std::string ClassName =
266 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
267 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *" << C2 << ") const {\n";
271 if (ClassName != "SDNode")
272 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
274 OS << Code << "\n}\n";
281 //===----------------------------------------------------------------------===//
282 // PatternCodeEmitter implementation.
284 class PatternCodeEmitter {
286 CodeGenDAGPatterns &CGP;
289 std::string PredicateCheck;
292 // Instruction selector pattern.
293 TreePatternNode *Pattern;
294 // Matched instruction.
295 TreePatternNode *Instruction;
297 // Node to name mapping
298 std::map<std::string, std::string> VariableMap;
299 // Node to operator mapping
300 std::map<std::string, Record*> OperatorMap;
301 // Name of the folded node which produces a flag.
302 std::pair<std::string, unsigned> FoldedFlag;
303 // Names of all the folded nodes which produce chains.
304 std::vector<std::pair<std::string, unsigned> > FoldedChains;
305 // Original input chain(s).
306 std::vector<std::pair<std::string, std::string> > OrigChains;
307 std::set<std::string> Duplicates;
309 /// LSI - Load/Store information.
310 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
311 /// for each memory access. This facilitates the use of AliasAnalysis in
313 std::vector<std::string> LSI;
315 /// GeneratedCode - This is the buffer that we emit code to. The first int
316 /// indicates whether this is an exit predicate (something that should be
317 /// tested, and if true, the match fails) [when 1], or normal code to emit
318 /// [when 0], or initialization code to emit [when 2].
319 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
320 /// GeneratedDecl - This is the set of all SDValue declarations needed for
321 /// the set of patterns for each top-level opcode.
322 std::set<std::string> &GeneratedDecl;
323 /// TargetOpcodes - The target specific opcodes used by the resulting
325 std::vector<std::string> &TargetOpcodes;
326 std::vector<std::string> &TargetVTs;
327 /// OutputIsVariadic - Records whether the instruction output pattern uses
328 /// variable_ops. This requires that the Emit function be passed an
329 /// additional argument to indicate where the input varargs operands
331 bool &OutputIsVariadic;
332 /// NumInputRootOps - Records the number of operands the root node of the
333 /// input pattern has. This information is used in the generated code to
334 /// pass to Emit functions when variable_ops processing is needed.
335 unsigned &NumInputRootOps;
337 std::string ChainName;
342 void emitCheck(const std::string &S) {
344 GeneratedCode.push_back(std::make_pair(1, S));
346 void emitCode(const std::string &S) {
348 GeneratedCode.push_back(std::make_pair(0, S));
350 void emitInit(const std::string &S) {
352 GeneratedCode.push_back(std::make_pair(2, S));
354 void emitDecl(const std::string &S) {
355 assert(!S.empty() && "Invalid declaration");
356 GeneratedDecl.insert(S);
358 void emitOpcode(const std::string &Opc) {
359 TargetOpcodes.push_back(Opc);
362 void emitVT(const std::string &VT) {
363 TargetVTs.push_back(VT);
367 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
368 TreePatternNode *pattern, TreePatternNode *instr,
369 std::vector<std::pair<unsigned, std::string> > &gc,
370 std::set<std::string> &gd,
371 std::vector<std::string> &to,
372 std::vector<std::string> &tv,
375 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
376 GeneratedCode(gc), GeneratedDecl(gd),
377 TargetOpcodes(to), TargetVTs(tv),
378 OutputIsVariadic(oiv), NumInputRootOps(niro),
379 TmpNo(0), OpcNo(0), VTNo(0) {}
381 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
382 /// if the match fails. At this point, we already know that the opcode for N
383 /// matches, and the SDNode for the result has the RootName specified name.
384 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
385 const std::string &RootName, const std::string &ChainSuffix,
388 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
389 const std::string &RootName,
390 const std::string &ChainSuffix, bool &FoundChain);
392 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
393 /// we actually have to build a DAG!
394 std::vector<std::string>
395 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
396 bool InFlagDecled, bool ResNodeDecled,
397 bool LikeLeaf = false, bool isRoot = false);
399 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
400 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
401 /// 'Pat' may be missing types. If we find an unresolved type to add a check
402 /// for, this returns true otherwise false if Pat has all types.
403 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
404 const std::string &Prefix, bool isRoot = false) {
406 if (Pat->getExtTypes() != Other->getExtTypes()) {
407 // Move a type over from 'other' to 'pat'.
408 Pat->setTypes(Other->getExtTypes());
409 // The top level node type is checked outside of the select function.
411 emitCheck(Prefix + ".getValueType() == " +
412 getName(Pat->getTypeNum(0)));
416 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
417 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
418 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
419 Prefix + utostr(OpNo)))
425 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
427 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
428 bool &ChainEmitted, bool &InFlagDecled,
429 bool &ResNodeDecled, bool isRoot = false) {
430 const CodeGenTarget &T = CGP.getTargetInfo();
431 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
432 bool HasInFlag = N->NodeHasProperty(SDNPInFlag, CGP);
433 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
434 TreePatternNode *Child = N->getChild(i);
435 if (!Child->isLeaf()) {
436 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
437 InFlagDecled, ResNodeDecled);
439 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
440 if (!Child->getName().empty()) {
441 std::string Name = RootName + utostr(OpNo);
442 if (Duplicates.find(Name) != Duplicates.end())
443 // A duplicate! Do not emit a copy for this node.
447 Record *RR = DI->getDef();
448 if (RR->isSubClassOf("Register")) {
449 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
450 if (RVT == MVT::Flag) {
452 emitCode("SDValue InFlag = " +
453 getValueName(RootName + utostr(OpNo)) + ";");
456 emitCode("InFlag = " +
457 getValueName(RootName + utostr(OpNo)) + ";");
460 emitCode("SDValue Chain = CurDAG->getEntryNode();");
465 emitCode("SDValue InFlag(0, 0);");
468 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
469 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
470 ", " + getNodeName(RootName) + "->getDebugLoc()" +
471 ", " + getQualifiedName(RR) +
472 ", " + getValueName(RootName + utostr(OpNo)) +
473 ", InFlag).getNode();");
474 ResNodeDecled = true;
475 emitCode(ChainName + " = SDValue(ResNode, 0);");
476 emitCode("InFlag = SDValue(ResNode, 1);");
485 emitCode("SDValue InFlag = " + getNodeName(RootName) +
486 "->getOperand(" + utostr(OpNo) + ");");
489 emitCode("InFlag = " + getNodeName(RootName) +
490 "->getOperand(" + utostr(OpNo) + ");");
496 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
497 /// if the match fails. At this point, we already know that the opcode for N
498 /// matches, and the SDNode for the result has the RootName specified name.
499 void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
500 const std::string &RootName,
501 const std::string &ChainSuffix,
503 // Save loads/stores matched by a pattern.
504 if (!N->isLeaf() && N->getName().empty()) {
505 if (N->NodeHasProperty(SDNPMemOperand, CGP))
506 LSI.push_back(getNodeName(RootName));
509 bool isRoot = (P == NULL);
510 // Emit instruction predicates. Each predicate is just a string for now.
512 // Record input varargs info.
513 NumInputRootOps = N->getNumChildren();
514 emitCheck(PredicateCheck);
518 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
519 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
520 ")->getSExtValue() == INT64_C(" +
521 itostr(II->getValue()) + ")");
524 assert(N->getComplexPatternInfo(CGP) != 0 &&
525 "Cannot match this as a leaf value!");
528 // If this node has a name associated with it, capture it in VariableMap. If
529 // we already saw this in the pattern, emit code to verify dagness.
530 if (!N->getName().empty()) {
531 std::string &VarMapEntry = VariableMap[N->getName()];
532 if (VarMapEntry.empty()) {
533 VarMapEntry = RootName;
535 // If we get here, this is a second reference to a specific name. Since
536 // we already have checked that the first reference is valid, we don't
537 // have to recursively match it, just check that it's the same as the
538 // previously named thing.
539 emitCheck(VarMapEntry + " == " + RootName);
544 OperatorMap[N->getName()] = N->getOperator();
548 // Emit code to load the child nodes and match their contents recursively.
550 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
551 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
556 // Check if it's profitable to fold the node. e.g. Check for multiple uses
558 std::string ParentName(RootName.begin(), RootName.end()-1);
560 // If this is just an interior node, check to see if it has a single
561 // use. If the node has multiple uses and the pattern has a load as
562 // an operand, then we can't fold the load.
563 emitCheck(getValueName(RootName) + ".hasOneUse()");
564 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
565 // If the immediate use can somehow reach this node through another
566 // path, then can't fold it either or it will create a cycle.
567 // e.g. In the following diagram, XX can reach ld through YY. If
568 // ld is folded into XX, then YY is both a predecessor and a successor
579 // We know we need the check if N's parent is not the root.
580 bool NeedCheck = P != Pattern;
582 // If the parent is the root and the node has more than one operand,
584 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
586 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
587 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
588 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
589 PInfo.getNumOperands() > 1 ||
590 PInfo.hasProperty(SDNPHasChain) ||
591 PInfo.hasProperty(SDNPInFlag) ||
592 PInfo.hasProperty(SDNPOptInFlag);
596 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
597 ", " + getNodeName(ParentName) + ", N)");
598 emitCheck("IsLegalToFold(" + getValueName(RootName) +
599 ", " + getNodeName(ParentName) + ", N)");
601 // Otherwise, just verify that the node only has a single use.
602 emitCheck(getValueName(RootName) + ".hasOneUse()");
609 emitCheck("(" + ChainName + ".getNode() == " +
610 getNodeName(RootName) + " || "
611 "IsChainCompatible(" + ChainName + ".getNode(), " +
612 getNodeName(RootName) + "))");
613 OrigChains.push_back(std::make_pair(ChainName,
614 getValueName(RootName)));
617 ChainName = "Chain" + ChainSuffix;
619 if (!N->getComplexPatternInfo(CGP) ||
621 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
626 // If there are node predicates for this, emit the calls.
627 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
628 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
630 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
631 // a constant without a predicate fn that has more that one bit set, handle
632 // this as a special case. This is usually for targets that have special
633 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
634 // handling stuff). Using these instructions is often far more efficient
635 // than materializing the constant. Unfortunately, both the instcombiner
636 // and the dag combiner can often infer that bits are dead, and thus drop
637 // them from the mask in the dag. For example, it might turn 'AND X, 255'
638 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
641 (N->getOperator()->getName() == "and" ||
642 N->getOperator()->getName() == "or") &&
643 N->getChild(1)->isLeaf() &&
644 N->getChild(1)->getPredicateFns().empty()) {
645 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
646 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
647 emitInit("SDValue " + RootName + "0" + " = " +
648 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
649 emitInit("SDValue " + RootName + "1" + " = " +
650 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
652 unsigned NTmp = TmpNo++;
653 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
654 " = dyn_cast<ConstantSDNode>(" +
655 getNodeName(RootName + "1") + ");");
656 emitCheck("Tmp" + utostr(NTmp));
657 const char *MaskPredicate = N->getOperator()->getName() == "or"
658 ? "CheckOrMask(" : "CheckAndMask(";
659 emitCheck(MaskPredicate + getValueName(RootName + "0") +
660 ", Tmp" + utostr(NTmp) +
661 ", INT64_C(" + itostr(II->getValue()) + "))");
663 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
664 ChainSuffix + utostr(0), FoundChain);
670 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
671 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
672 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
674 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
675 ChainSuffix + utostr(OpNo), FoundChain);
678 // Handle cases when root is a complex pattern.
679 const ComplexPattern *CP;
680 if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
681 std::string Fn = CP->getSelectFunc();
682 unsigned NumOps = CP->getNumOperands();
683 for (unsigned i = 0; i < NumOps; ++i) {
684 emitDecl("CPTmp" + RootName + "_" + utostr(i));
685 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
687 if (CP->hasProperty(SDNPHasChain)) {
688 emitDecl("CPInChain");
689 emitDecl("Chain" + ChainSuffix);
690 emitCode("SDValue CPInChain;");
691 emitCode("SDValue Chain" + ChainSuffix + ";");
694 std::string Code = Fn + "(N, "; // always pass in the root.
695 Code += getValueName(RootName);
696 for (unsigned i = 0; i < NumOps; i++)
697 Code += ", CPTmp" + RootName + "_" + utostr(i);
698 if (CP->hasProperty(SDNPHasChain)) {
699 ChainName = "Chain" + ChainSuffix;
700 Code += ", CPInChain, Chain" + ChainSuffix;
702 emitCheck(Code + ")");
706 void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
707 TreePatternNode *Parent,
708 const std::string &RootName,
709 const std::string &ChainSuffix,
711 if (!Child->isLeaf()) {
712 // If it's not a leaf, recursively match.
713 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
714 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
715 CInfo.getEnumName());
716 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
717 bool HasChain = false;
718 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
720 FoldedChains.push_back(std::make_pair(getValueName(RootName),
721 CInfo.getNumResults()));
723 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
724 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
725 "Pattern folded multiple nodes which produce flags?");
726 FoldedFlag = std::make_pair(getValueName(RootName),
727 CInfo.getNumResults() + (unsigned)HasChain);
732 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
733 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
734 bool HasChain = false;
736 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
738 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
739 FoldedChains.push_back(std::make_pair("CPInChain",
740 PInfo.getNumResults()));
742 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
743 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
744 "Pattern folded multiple nodes which produce flags?");
745 FoldedFlag = std::make_pair(getValueName(RootName),
746 CP->getNumOperands() + (unsigned)HasChain);
751 // If this child has a name associated with it, capture it in VarMap. If
752 // we already saw this in the pattern, emit code to verify dagness.
753 if (!Child->getName().empty()) {
754 std::string &VarMapEntry = VariableMap[Child->getName()];
755 if (VarMapEntry.empty()) {
756 VarMapEntry = getValueName(RootName);
758 // If we get here, this is a second reference to a specific name.
759 // Since we already have checked that the first reference is valid,
760 // we don't have to recursively match it, just check that it's the
761 // same as the previously named thing.
762 emitCheck(VarMapEntry + " == " + getValueName(RootName));
763 Duplicates.insert(getValueName(RootName));
768 // Handle leaves of various types.
769 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
770 Record *LeafRec = DI->getDef();
771 if (LeafRec->isSubClassOf("RegisterClass") ||
772 LeafRec->isSubClassOf("PointerLikeRegClass")) {
773 // Handle register references. Nothing to do here.
774 } else if (LeafRec->isSubClassOf("Register")) {
775 // Handle register references.
776 } else if (LeafRec->getName() == "srcvalue") {
777 // Place holder for SRCVALUE nodes. Nothing to do here.
778 } else if (LeafRec->isSubClassOf("ValueType")) {
779 // Make sure this is the specified value type.
780 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
781 ")->getVT() == MVT::" + LeafRec->getName());
782 } else if (LeafRec->isSubClassOf("CondCode")) {
783 // Make sure this is the specified cond code.
784 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
785 ")->get() == ISD::" + LeafRec->getName());
791 assert(0 && "Unknown leaf type!");
794 // If there are node predicates for this, emit the calls.
795 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
796 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
801 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
802 unsigned NTmp = TmpNo++;
803 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
804 " = dyn_cast<ConstantSDNode>("+
805 getNodeName(RootName) + ");");
806 emitCheck("Tmp" + utostr(NTmp));
807 unsigned CTmp = TmpNo++;
808 emitCode("int64_t CN"+ utostr(CTmp) +
809 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
810 emitCheck("CN" + utostr(CTmp) + " == "
811 "INT64_C(" +itostr(II->getValue()) + ")");
817 assert(0 && "Unknown leaf type!");
820 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
821 /// we actually have to build a DAG!
822 std::vector<std::string>
823 PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
824 std::vector<Record*> DstRegs,
825 bool InFlagDecled, bool ResNodeDecled,
826 bool LikeLeaf, bool isRoot) {
827 // List of arguments of getMachineNode() or SelectNodeTo().
828 std::vector<std::string> NodeOps;
829 // This is something selected from the pattern we matched.
830 if (!N->getName().empty()) {
831 const std::string &VarName = N->getName();
832 std::string Val = VariableMap[VarName];
833 bool ModifiedVal = false;
835 errs() << "Variable '" << VarName << " referenced but not defined "
836 << "and not caught earlier!\n";
839 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
840 // Already selected this operand, just return the tmpval.
841 NodeOps.push_back(getValueName(Val));
845 const ComplexPattern *CP;
846 unsigned ResNo = TmpNo++;
847 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
848 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
849 std::string CastType;
850 std::string TmpVar = "Tmp" + utostr(ResNo);
851 switch (N->getTypeNum(0)) {
853 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
854 << " type as an immediate constant. Aborting\n";
856 case MVT::i1: CastType = "bool"; break;
857 case MVT::i8: CastType = "unsigned char"; break;
858 case MVT::i16: CastType = "unsigned short"; break;
859 case MVT::i32: CastType = "unsigned"; break;
860 case MVT::i64: CastType = "uint64_t"; break;
862 emitCode("SDValue " + TmpVar +
863 " = CurDAG->getTargetConstant(((" + CastType +
864 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
865 getEnumName(N->getTypeNum(0)) + ");");
866 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
867 // value if used multiple times by this pattern result.
870 NodeOps.push_back(getValueName(Val));
871 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
872 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
873 std::string TmpVar = "Tmp" + utostr(ResNo);
874 emitCode("SDValue " + TmpVar +
875 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
876 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
877 Val + ")->getValueType(0));");
878 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
879 // value if used multiple times by this pattern result.
882 NodeOps.push_back(getValueName(Val));
883 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
884 Record *Op = OperatorMap[N->getName()];
885 // Transform ExternalSymbol to TargetExternalSymbol
886 if (Op && Op->getName() == "externalsym") {
887 std::string TmpVar = "Tmp"+utostr(ResNo);
888 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
889 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
890 Val + ")->getSymbol(), " +
891 getEnumName(N->getTypeNum(0)) + ");");
892 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
893 // this value if used multiple times by this pattern result.
897 NodeOps.push_back(getValueName(Val));
898 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
899 || N->getOperator()->getName() == "tglobaltlsaddr")) {
900 Record *Op = OperatorMap[N->getName()];
901 // Transform GlobalAddress to TargetGlobalAddress
902 if (Op && (Op->getName() == "globaladdr" ||
903 Op->getName() == "globaltlsaddr")) {
904 std::string TmpVar = "Tmp" + utostr(ResNo);
905 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
906 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
907 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
909 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
910 // this value if used multiple times by this pattern result.
914 NodeOps.push_back(getValueName(Val));
915 } else if (!N->isLeaf()
916 && (N->getOperator()->getName() == "texternalsym" ||
917 N->getOperator()->getName() == "tconstpool")) {
918 // Do not rewrite the variable name, since we don't generate a new
920 NodeOps.push_back(getValueName(Val));
921 } else if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
922 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
923 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
926 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
927 // node even if it isn't one. Don't select it.
929 if (isRoot && N->isLeaf()) {
930 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
931 emitCode("return NULL;");
934 NodeOps.push_back(getValueName(Val));
938 VariableMap[VarName] = Val;
942 // If this is an explicit register reference, handle it.
943 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
944 unsigned ResNo = TmpNo++;
945 if (DI->getDef()->isSubClassOf("Register")) {
946 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
947 getQualifiedName(DI->getDef()) + ", " +
948 getEnumName(N->getTypeNum(0)) + ");");
949 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
951 } else if (DI->getDef()->getName() == "zero_reg") {
952 emitCode("SDValue Tmp" + utostr(ResNo) +
953 " = CurDAG->getRegister(0, " +
954 getEnumName(N->getTypeNum(0)) + ");");
955 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
957 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
958 // Handle a reference to a register class. This is used
959 // in COPY_TO_SUBREG instructions.
960 emitCode("SDValue Tmp" + utostr(ResNo) +
961 " = CurDAG->getTargetConstant(" +
962 getQualifiedName(DI->getDef()) + "RegClassID, " +
964 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
967 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
968 unsigned ResNo = TmpNo++;
969 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
970 emitCode("SDValue Tmp" + utostr(ResNo) +
971 " = CurDAG->getTargetConstant(0x" +
972 utohexstr((uint64_t) II->getValue()) +
973 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
974 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
981 assert(0 && "Unknown leaf type!");
985 Record *Op = N->getOperator();
986 if (Op->isSubClassOf("Instruction")) {
987 const CodeGenTarget &CGT = CGP.getTargetInfo();
988 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
989 const DAGInstruction &Inst = CGP.getInstruction(Op);
990 const TreePattern *InstPat = Inst.getPattern();
991 // FIXME: Assume actual pattern comes before "implicit".
992 TreePatternNode *InstPatNode =
993 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
994 : (InstPat ? InstPat->getTree(0) : NULL);
995 if (InstPatNode && !InstPatNode->isLeaf() &&
996 InstPatNode->getOperator()->getName() == "set") {
997 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
999 bool IsVariadic = isRoot && II.isVariadic;
1000 // FIXME: fix how we deal with physical register operands.
1001 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1002 bool HasImpResults = isRoot && DstRegs.size() > 0;
1003 bool NodeHasOptInFlag = isRoot &&
1004 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
1005 bool NodeHasInFlag = isRoot &&
1006 Pattern->TreeHasProperty(SDNPInFlag, CGP);
1007 bool NodeHasOutFlag = isRoot &&
1008 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
1009 bool NodeHasChain = InstPatNode &&
1010 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
1011 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
1012 unsigned NumResults = Inst.getNumResults();
1013 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1015 // Record output varargs info.
1016 OutputIsVariadic = IsVariadic;
1018 if (NodeHasOptInFlag) {
1019 emitCode("bool HasInFlag = "
1020 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1024 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1026 // How many results is this pattern expected to produce?
1027 unsigned NumPatResults = 0;
1028 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1029 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1030 if (VT != MVT::isVoid && VT != MVT::Flag)
1034 if (OrigChains.size() > 0) {
1035 // The original input chain is being ignored. If it is not just
1036 // pointing to the op that's being folded, we should create a
1037 // TokenFactor with it and the chain of the folded op as the new chain.
1038 // We could potentially be doing multiple levels of folding, in that
1039 // case, the TokenFactor can have more operands.
1040 emitCode("SmallVector<SDValue, 8> InChains;");
1041 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1042 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1043 OrigChains[i].second + ".getNode()) {");
1044 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1047 emitCode("InChains.push_back(" + ChainName + ");");
1048 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1049 "N->getDebugLoc(), MVT::Other, "
1050 "&InChains[0], InChains.size());");
1052 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1053 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1057 // Loop over all of the operands of the instruction pattern, emitting code
1058 // to fill them all in. The node 'N' usually has number children equal to
1059 // the number of input operands of the instruction. However, in cases
1060 // where there are predicate operands for an instruction, we need to fill
1061 // in the 'execute always' values. Match up the node operands to the
1062 // instruction operands to do this.
1063 std::vector<std::string> AllOps;
1064 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1065 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1066 std::vector<std::string> Ops;
1068 // Determine what to emit for this operand.
1069 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1070 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1071 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1072 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1073 // This is a predicate or optional def operand; emit the
1074 // 'default ops' operands.
1075 const DAGDefaultOperand &DefaultOp =
1076 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1077 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1078 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1079 InFlagDecled, ResNodeDecled);
1080 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1083 // Otherwise this is a normal operand or a predicate operand without
1084 // 'execute always'; emit it.
1085 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1086 InFlagDecled, ResNodeDecled);
1087 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1092 // Emit all the chain and CopyToReg stuff.
1093 bool ChainEmitted = NodeHasChain;
1094 if (NodeHasInFlag || HasImpInputs)
1095 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1096 InFlagDecled, ResNodeDecled, true);
1097 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1098 if (!InFlagDecled) {
1099 emitCode("SDValue InFlag(0, 0);");
1100 InFlagDecled = true;
1102 if (NodeHasOptInFlag) {
1103 emitCode("if (HasInFlag) {");
1104 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1109 unsigned ResNo = TmpNo++;
1111 unsigned OpsNo = OpcNo;
1112 std::string CodePrefix;
1113 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1114 std::deque<std::string> After;
1115 std::string NodeName;
1117 NodeName = "Tmp" + utostr(ResNo);
1118 CodePrefix = "SDValue " + NodeName + "(";
1120 NodeName = "ResNode";
1121 if (!ResNodeDecled) {
1122 CodePrefix = "SDNode *" + NodeName + " = ";
1123 ResNodeDecled = true;
1125 CodePrefix = NodeName + " = ";
1128 std::string Code = "Opc" + utostr(OpcNo);
1130 if (!isRoot || (InputHasChain && !NodeHasChain))
1131 // For call to "getMachineNode()".
1132 Code += ", N->getDebugLoc()";
1134 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1136 // Output order: results, chain, flags
1138 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1139 Code += ", VT" + utostr(VTNo);
1140 emitVT(getEnumName(N->getTypeNum(0)));
1142 // Add types for implicit results in physical registers, scheduler will
1143 // care of adding copyfromreg nodes.
1144 for (unsigned i = 0; i < NumDstRegs; i++) {
1145 Record *RR = DstRegs[i];
1146 if (RR->isSubClassOf("Register")) {
1147 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1148 Code += ", " + getEnumName(RVT);
1152 Code += ", MVT::Other";
1154 Code += ", MVT::Flag";
1158 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1159 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1162 // Figure out whether any operands at the end of the op list are not
1163 // part of the variable section.
1164 std::string EndAdjust;
1165 if (NodeHasInFlag || HasImpInputs)
1166 EndAdjust = "-1"; // Always has one flag.
1167 else if (NodeHasOptInFlag)
1168 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1170 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1171 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1173 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1177 // Populate MemRefs with entries for each memory accesses covered by
1179 if (isRoot && !LSI.empty()) {
1180 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1181 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1182 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1183 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1184 emitCode(MemRefs + "[" + utostr(i) + "] = "
1185 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1186 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1187 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1193 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1195 AllOps.push_back(ChainName);
1199 if (NodeHasInFlag || HasImpInputs)
1200 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1201 else if (NodeHasOptInFlag) {
1202 emitCode("if (HasInFlag)");
1203 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1205 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1207 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1208 AllOps.push_back("InFlag");
1210 unsigned NumOps = AllOps.size();
1212 if (!NodeHasOptInFlag && NumOps < 4) {
1213 for (unsigned i = 0; i != NumOps; ++i)
1214 Code += ", " + AllOps[i];
1216 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1217 for (unsigned i = 0; i != NumOps; ++i) {
1218 OpsCode += AllOps[i];
1222 emitCode(OpsCode + " };");
1223 Code += ", Ops" + utostr(OpsNo) + ", ";
1224 if (NodeHasOptInFlag) {
1225 Code += "HasInFlag ? ";
1226 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1228 Code += utostr(NumOps);
1235 std::vector<std::string> ReplaceFroms;
1236 std::vector<std::string> ReplaceTos;
1238 NodeOps.push_back("Tmp" + utostr(ResNo));
1241 if (NodeHasOutFlag) {
1242 if (!InFlagDecled) {
1243 After.push_back("SDValue InFlag(ResNode, " +
1244 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1246 InFlagDecled = true;
1248 After.push_back("InFlag = SDValue(ResNode, " +
1249 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1253 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1254 ReplaceFroms.push_back("SDValue(" +
1255 FoldedChains[j].first + ".getNode(), " +
1256 utostr(FoldedChains[j].second) +
1258 ReplaceTos.push_back("SDValue(ResNode, " +
1259 utostr(NumResults+NumDstRegs) + ")");
1262 if (NodeHasOutFlag) {
1263 if (FoldedFlag.first != "") {
1264 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1265 utostr(FoldedFlag.second) + ")");
1266 ReplaceTos.push_back("InFlag");
1268 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
1269 ReplaceFroms.push_back("SDValue(N, " +
1270 utostr(NumPatResults + (unsigned)InputHasChain)
1272 ReplaceTos.push_back("InFlag");
1276 if (!ReplaceFroms.empty() && InputHasChain) {
1277 ReplaceFroms.push_back("SDValue(N, " +
1278 utostr(NumPatResults) + ")");
1279 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1280 ChainName + ".getResNo()" + ")");
1281 ChainAssignmentNeeded |= NodeHasChain;
1284 // User does not expect the instruction would produce a chain!
1285 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1287 } else if (InputHasChain && !NodeHasChain) {
1288 // One of the inner node produces a chain.
1289 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1290 ReplaceFroms.push_back("SDValue(N, " +
1291 utostr(NumPatResults) + ")");
1292 ReplaceTos.push_back(ChainName);
1296 if (ChainAssignmentNeeded) {
1297 // Remember which op produces the chain.
1298 std::string ChainAssign;
1300 ChainAssign = ChainName + " = SDValue(" + NodeName +
1301 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1303 ChainAssign = ChainName + " = SDValue(" + NodeName +
1304 ", " + utostr(NumResults+NumDstRegs) + ");";
1306 After.push_front(ChainAssign);
1309 if (ReplaceFroms.size() == 1) {
1310 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1311 ReplaceTos[0] + ");");
1312 } else if (!ReplaceFroms.empty()) {
1313 After.push_back("const SDValue Froms[] = {");
1314 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1315 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1316 After.push_back("};");
1317 After.push_back("const SDValue Tos[] = {");
1318 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1319 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1320 After.push_back("};");
1321 After.push_back("ReplaceUses(Froms, Tos, " +
1322 itostr(ReplaceFroms.size()) + ");");
1325 // We prefer to use SelectNodeTo since it avoids allocation when
1326 // possible and it avoids CSE map recalculation for the node's
1327 // users, however it's tricky to use in a non-root context.
1329 // We also don't use SelectNodeTo if the pattern replacement is being
1330 // used to jettison a chain result, since morphing the node in place
1331 // would leave users of the chain dangling.
1333 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1334 Code = "CurDAG->getMachineNode(" + Code;
1336 Code = "CurDAG->SelectNodeTo(N, " + Code;
1340 CodePrefix = "return ";
1342 After.push_back("return ResNode;");
1345 emitCode(CodePrefix + Code + ");");
1349 emitCode("CurDAG->setSubgraphColor(" +
1350 NodeName +".getNode(), \"yellow\");");
1351 emitCode("CurDAG->setSubgraphColor(" +
1352 NodeName +".getNode(), \"black\");");
1354 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1355 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1359 for (unsigned i = 0, e = After.size(); i != e; ++i)
1364 if (Op->isSubClassOf("SDNodeXForm")) {
1365 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1366 // PatLeaf node - the operand may or may not be a leaf node. But it should
1368 std::vector<std::string> Ops =
1369 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1370 ResNodeDecled, true);
1371 unsigned ResNo = TmpNo++;
1372 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1373 + "(" + Ops.back() + ".getNode());");
1374 NodeOps.push_back("Tmp" + utostr(ResNo));
1376 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1382 throw std::string("Unknown node in result pattern!");
1386 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1387 /// stream to match the pattern, and generate the code for the match if it
1388 /// succeeds. Returns true if the pattern is not guaranteed to match.
1389 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1390 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1391 std::set<std::string> &GeneratedDecl,
1392 std::vector<std::string> &TargetOpcodes,
1393 std::vector<std::string> &TargetVTs,
1394 bool &OutputIsVariadic,
1395 unsigned &NumInputRootOps) {
1396 OutputIsVariadic = false;
1397 NumInputRootOps = 0;
1399 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1400 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1401 GeneratedCode, GeneratedDecl,
1402 TargetOpcodes, TargetVTs,
1403 OutputIsVariadic, NumInputRootOps);
1405 // Emit the matcher, capturing named arguments in VariableMap.
1406 bool FoundChain = false;
1407 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1409 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1410 // diagnostics, which we know are impossible at this point.
1411 TreePattern &TP = *CGP.pf_begin()->second;
1413 // At this point, we know that we structurally match the pattern, but the
1414 // types of the nodes may not match. Figure out the fewest number of type
1415 // comparisons we need to emit. For example, if there is only one integer
1416 // type supported by a target, there should be no type comparisons at all for
1417 // integer patterns!
1419 // To figure out the fewest number of type checks needed, clone the pattern,
1420 // remove the types, then perform type inference on the pattern as a whole.
1421 // If there are unresolved types, emit an explicit check for those types,
1422 // apply the type to the tree, then rerun type inference. Iterate until all
1423 // types are resolved.
1425 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1426 Pat->RemoveAllTypes();
1429 // Resolve/propagate as many types as possible.
1431 bool MadeChange = true;
1433 MadeChange = Pat->ApplyTypeConstraints(TP,
1434 true/*Ignore reg constraints*/);
1436 assert(0 && "Error: could not find consistent types for something we"
1437 " already decided was ok!");
1441 // Insert a check for an unresolved type and add it to the tree. If we find
1442 // an unresolved type to add a check for, this returns true and we iterate,
1443 // otherwise we are done.
1444 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1446 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1447 false, false, false, true);
1451 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1452 /// a line causes any of them to be empty, remove them and return true when
1454 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1455 std::vector<std::pair<unsigned, std::string> > > >
1457 bool ErasedPatterns = false;
1458 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1459 Patterns[i].second.pop_back();
1460 if (Patterns[i].second.empty()) {
1461 Patterns.erase(Patterns.begin()+i);
1463 ErasedPatterns = true;
1466 return ErasedPatterns;
1469 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1470 /// code together between the patterns.
1471 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1472 std::vector<std::pair<unsigned, std::string> > > >
1473 &Patterns, unsigned Indent,
1475 typedef std::pair<unsigned, std::string> CodeLine;
1476 typedef std::vector<CodeLine> CodeList;
1477 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1479 if (Patterns.empty()) return;
1481 // Figure out how many patterns share the next code line. Explicitly copy
1482 // FirstCodeLine so that we don't invalidate a reference when changing
1484 const CodeLine FirstCodeLine = Patterns.back().second.back();
1485 unsigned LastMatch = Patterns.size()-1;
1486 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1489 // If not all patterns share this line, split the list into two pieces. The
1490 // first chunk will use this line, the second chunk won't.
1491 if (LastMatch != 0) {
1492 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1493 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1495 // FIXME: Emit braces?
1496 if (Shared.size() == 1) {
1497 const PatternToMatch &Pattern = *Shared.back().first;
1498 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1499 Pattern.getSrcPattern()->print(OS);
1500 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1501 Pattern.getDstPattern()->print(OS);
1503 unsigned AddedComplexity = Pattern.getAddedComplexity();
1504 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1505 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1507 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1509 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1511 if (FirstCodeLine.first != 1) {
1512 OS << std::string(Indent, ' ') << "{\n";
1515 EmitPatterns(Shared, Indent, OS);
1516 if (FirstCodeLine.first != 1) {
1518 OS << std::string(Indent, ' ') << "}\n";
1521 if (Other.size() == 1) {
1522 const PatternToMatch &Pattern = *Other.back().first;
1523 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1524 Pattern.getSrcPattern()->print(OS);
1525 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1526 Pattern.getDstPattern()->print(OS);
1528 unsigned AddedComplexity = Pattern.getAddedComplexity();
1529 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1530 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1532 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1534 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1536 EmitPatterns(Other, Indent, OS);
1540 // Remove this code from all of the patterns that share it.
1541 bool ErasedPatterns = EraseCodeLine(Patterns);
1543 bool isPredicate = FirstCodeLine.first == 1;
1545 // Otherwise, every pattern in the list has this line. Emit it.
1548 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1550 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1552 // If the next code line is another predicate, and if all of the pattern
1553 // in this group share the same next line, emit it inline now. Do this
1554 // until we run out of common predicates.
1555 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1556 // Check that all of the patterns in Patterns end with the same predicate.
1557 bool AllEndWithSamePredicate = true;
1558 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1559 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1560 AllEndWithSamePredicate = false;
1563 // If all of the predicates aren't the same, we can't share them.
1564 if (!AllEndWithSamePredicate) break;
1566 // Otherwise we can. Emit it shared now.
1567 OS << " &&\n" << std::string(Indent+4, ' ')
1568 << Patterns.back().second.back().second;
1569 ErasedPatterns = EraseCodeLine(Patterns);
1576 EmitPatterns(Patterns, Indent, OS);
1579 OS << std::string(Indent-2, ' ') << "}\n";
1582 static std::string getLegalCName(std::string OpName) {
1583 std::string::size_type pos = OpName.find("::");
1584 if (pos != std::string::npos)
1585 OpName.replace(pos, 2, "_");
1589 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1590 const CodeGenTarget &Target = CGP.getTargetInfo();
1592 // Get the namespace to insert instructions into.
1593 std::string InstNS = Target.getInstNamespace();
1594 if (!InstNS.empty()) InstNS += "::";
1596 // Group the patterns by their top-level opcodes.
1597 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1598 // All unique target node emission functions.
1599 std::map<std::string, unsigned> EmitFunctions;
1600 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1601 E = CGP.ptm_end(); I != E; ++I) {
1602 const PatternToMatch &Pattern = *I;
1603 TreePatternNode *Node = Pattern.getSrcPattern();
1604 if (!Node->isLeaf()) {
1605 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1606 push_back(&Pattern);
1608 const ComplexPattern *CP;
1609 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1610 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1611 push_back(&Pattern);
1612 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
1613 std::vector<Record*> OpNodes = CP->getRootNodes();
1614 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1615 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1616 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1620 errs() << "Unrecognized opcode '";
1622 errs() << "' on tree pattern '";
1623 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1629 // For each opcode, there might be multiple select functions, one per
1630 // ValueType of the node (or its first operand if it doesn't produce a
1631 // non-chain result.
1632 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1634 // Emit one Select_* method for each top-level opcode. We do this instead of
1635 // emitting one giant switch statement to support compilers where this will
1636 // result in the recursive functions taking less stack space.
1637 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1638 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1639 PBOI != E; ++PBOI) {
1640 const std::string &OpName = PBOI->first;
1641 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1642 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1644 // Split them into groups by type.
1645 std::map<MVT::SimpleValueType,
1646 std::vector<const PatternToMatch*> > PatternsByType;
1647 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1648 const PatternToMatch *Pat = PatternsOfOp[i];
1649 TreePatternNode *SrcPat = Pat->getSrcPattern();
1650 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1653 for (std::map<MVT::SimpleValueType,
1654 std::vector<const PatternToMatch*> >::iterator
1655 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1657 MVT::SimpleValueType OpVT = II->first;
1658 std::vector<const PatternToMatch*> &Patterns = II->second;
1659 typedef std::pair<unsigned, std::string> CodeLine;
1660 typedef std::vector<CodeLine> CodeList;
1661 typedef CodeList::iterator CodeListI;
1663 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1664 std::vector<std::vector<std::string> > PatternOpcodes;
1665 std::vector<std::vector<std::string> > PatternVTs;
1666 std::vector<std::set<std::string> > PatternDecls;
1667 std::vector<bool> OutputIsVariadicFlags;
1668 std::vector<unsigned> NumInputRootOpsCounts;
1669 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1670 CodeList GeneratedCode;
1671 std::set<std::string> GeneratedDecl;
1672 std::vector<std::string> TargetOpcodes;
1673 std::vector<std::string> TargetVTs;
1674 bool OutputIsVariadic;
1675 unsigned NumInputRootOps;
1676 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1677 TargetOpcodes, TargetVTs,
1678 OutputIsVariadic, NumInputRootOps);
1679 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1680 PatternDecls.push_back(GeneratedDecl);
1681 PatternOpcodes.push_back(TargetOpcodes);
1682 PatternVTs.push_back(TargetVTs);
1683 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1684 NumInputRootOpsCounts.push_back(NumInputRootOps);
1687 // Factor target node emission code (emitted by EmitResultCode) into
1688 // separate functions. Uniquing and share them among all instruction
1689 // selection routines.
1690 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1691 CodeList &GeneratedCode = CodeForPatterns[i].second;
1692 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1693 std::vector<std::string> &TargetVTs = PatternVTs[i];
1694 std::set<std::string> Decls = PatternDecls[i];
1695 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1696 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1697 std::vector<std::string> AddedInits;
1698 int CodeSize = (int)GeneratedCode.size();
1700 for (int j = CodeSize-1; j >= 0; --j) {
1701 if (LastPred == -1 && GeneratedCode[j].first == 1)
1703 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1704 AddedInits.push_back(GeneratedCode[j].second);
1707 std::string CalleeCode = "(SDNode *N";
1708 std::string CallerCode = "(N";
1709 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1710 CalleeCode += ", unsigned Opc" + utostr(j);
1711 CallerCode += ", " + TargetOpcodes[j];
1713 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1714 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1715 CallerCode += ", " + TargetVTs[j];
1717 for (std::set<std::string>::iterator
1718 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1719 std::string Name = *I;
1720 CalleeCode += ", SDValue &" + Name;
1721 CallerCode += ", " + Name;
1724 if (OutputIsVariadic) {
1725 CalleeCode += ", unsigned NumInputRootOps";
1726 CallerCode += ", " + utostr(NumInputRootOps);
1730 CalleeCode += ") {\n";
1732 for (std::vector<std::string>::const_reverse_iterator
1733 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1734 CalleeCode += " " + *I + "\n";
1736 for (int j = LastPred+1; j < CodeSize; ++j)
1737 CalleeCode += " " + GeneratedCode[j].second + "\n";
1738 for (int j = LastPred+1; j < CodeSize; ++j)
1739 GeneratedCode.pop_back();
1740 CalleeCode += "}\n";
1742 // Uniquing the emission routines.
1743 unsigned EmitFuncNum;
1744 std::map<std::string, unsigned>::iterator EFI =
1745 EmitFunctions.find(CalleeCode);
1746 if (EFI != EmitFunctions.end()) {
1747 EmitFuncNum = EFI->second;
1749 EmitFuncNum = EmitFunctions.size();
1750 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1751 // Prevent emission routines from being inlined to reduce selection
1752 // routines stack frame sizes.
1753 OS << "DISABLE_INLINE ";
1754 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1757 // Replace the emission code within selection routines with calls to the
1758 // emission functions.
1760 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
1761 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1762 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1764 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1765 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1766 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1767 GeneratedCode.push_back(std::make_pair(0, "}"));
1768 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
1770 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1774 std::string OpVTStr;
1775 if (OpVT == MVT::iPTR) {
1777 } else if (OpVT == MVT::iPTRAny) {
1778 OpVTStr = "_iPTRAny";
1779 } else if (OpVT == MVT::isVoid) {
1780 // Nodes with a void result actually have a first result type of either
1781 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1782 // void to this case, we handle it specially here.
1784 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1786 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1787 OpcodeVTMap.find(OpName);
1788 if (OpVTI == OpcodeVTMap.end()) {
1789 std::vector<std::string> VTSet;
1790 VTSet.push_back(OpVTStr);
1791 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1793 OpVTI->second.push_back(OpVTStr);
1795 // We want to emit all of the matching code now. However, we want to emit
1796 // the matches in order of minimal cost. Sort the patterns so the least
1797 // cost one is at the start.
1798 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1799 PatternSortingPredicate(CGP));
1801 // Scan the code to see if all of the patterns are reachable and if it is
1802 // possible that the last one might not match.
1803 bool mightNotMatch = true;
1804 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1805 CodeList &GeneratedCode = CodeForPatterns[i].second;
1806 mightNotMatch = false;
1808 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1809 if (GeneratedCode[j].first == 1) { // predicate.
1810 mightNotMatch = true;
1815 // If this pattern definitely matches, and if it isn't the last one, the
1816 // patterns after it CANNOT ever match. Error out.
1817 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1818 errs() << "Pattern '";
1819 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1820 errs() << "' is impossible to select!\n";
1825 // Loop through and reverse all of the CodeList vectors, as we will be
1826 // accessing them from their logical front, but accessing the end of a
1827 // vector is more efficient.
1828 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1829 CodeList &GeneratedCode = CodeForPatterns[i].second;
1830 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1833 // Next, reverse the list of patterns itself for the same reason.
1834 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1836 OS << "SDNode *Select_" << getLegalCName(OpName)
1837 << OpVTStr << "(SDNode *N) {\n";
1839 // Emit all of the patterns now, grouped together to share code.
1840 EmitPatterns(CodeForPatterns, 2, OS);
1842 // If the last pattern has predicates (which could fail) emit code to
1843 // catch the case where nothing handles a pattern.
1844 if (mightNotMatch) {
1846 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1847 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1848 OpName != "ISD::INTRINSIC_VOID")
1849 OS << " CannotYetSelect(N);\n";
1851 OS << " CannotYetSelectIntrinsic(N);\n";
1853 OS << " return NULL;\n";
1859 OS << "// The main instruction selector code.\n"
1860 << "SDNode *SelectCode(SDNode *N) {\n"
1861 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1862 << " switch (N->getOpcode()) {\n"
1864 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
1866 << " case ISD::EntryToken: // These nodes remain the same.\n"
1867 << " case ISD::BasicBlock:\n"
1868 << " case ISD::Register:\n"
1869 << " case ISD::HANDLENODE:\n"
1870 << " case ISD::TargetConstant:\n"
1871 << " case ISD::TargetConstantFP:\n"
1872 << " case ISD::TargetConstantPool:\n"
1873 << " case ISD::TargetFrameIndex:\n"
1874 << " case ISD::TargetExternalSymbol:\n"
1875 << " case ISD::TargetBlockAddress:\n"
1876 << " case ISD::TargetJumpTable:\n"
1877 << " case ISD::TargetGlobalTLSAddress:\n"
1878 << " case ISD::TargetGlobalAddress:\n"
1879 << " case ISD::TokenFactor:\n"
1880 << " case ISD::CopyFromReg:\n"
1881 << " case ISD::CopyToReg: {\n"
1882 << " return NULL;\n"
1884 << " case ISD::AssertSext:\n"
1885 << " case ISD::AssertZext: {\n"
1886 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
1887 << " return NULL;\n"
1889 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1890 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1891 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1893 // Loop over all of the case statements, emiting a call to each method we
1895 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1896 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1897 PBOI != E; ++PBOI) {
1898 const std::string &OpName = PBOI->first;
1899 // Potentially multiple versions of select for this opcode. One for each
1900 // ValueType of the node (or its first true operand if it doesn't produce a
1902 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1903 OpcodeVTMap.find(OpName);
1904 std::vector<std::string> &OpVTs = OpVTI->second;
1905 OS << " case " << OpName << ": {\n";
1906 // If we have only one variant and it's the default, elide the
1907 // switch. Marginally faster, and makes MSVC happier.
1908 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1909 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1914 // Keep track of whether we see a pattern that has an iPtr result.
1915 bool HasPtrPattern = false;
1916 bool HasDefaultPattern = false;
1918 OS << " switch (NVT) {\n";
1919 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1920 std::string &VTStr = OpVTs[i];
1921 if (VTStr.empty()) {
1922 HasDefaultPattern = true;
1926 // If this is a match on iPTR: don't emit it directly, we need special
1928 if (VTStr == "_iPTR") {
1929 HasPtrPattern = true;
1932 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1933 << " return Select_" << getLegalCName(OpName)
1934 << VTStr << "(N);\n";
1936 OS << " default:\n";
1938 // If there is an iPTR result version of this pattern, emit it here.
1939 if (HasPtrPattern) {
1940 OS << " if (TLI.getPointerTy() == NVT)\n";
1941 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1943 if (HasDefaultPattern) {
1944 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1952 OS << " } // end of big switch.\n\n"
1953 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1954 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1955 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
1956 << " CannotYetSelect(N);\n"
1958 << " CannotYetSelectIntrinsic(N);\n"
1960 << " return NULL;\n"
1964 void DAGISelEmitter::run(raw_ostream &OS) {
1965 EmitSourceFileHeader("DAG Instruction Selector for the " +
1966 CGP.getTargetInfo().getName() + " target", OS);
1968 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1969 << "// *** instruction selector class. These functions are really "
1972 OS << "// Include standard, target-independent definitions and methods used\n"
1973 << "// by the instruction selector.\n";
1974 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
1976 EmitNodeTransforms(OS);
1977 EmitPredicateFunctions(OS);
1979 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
1980 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1982 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1983 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1984 DEBUG(errs() << "\n");
1987 // At this point, we have full information about the 'Patterns' we need to
1988 // parse, both implicitly from instructions as well as from explicit pattern
1989 // definitions. Emit the resultant instruction selector.
1990 EmitInstructionSelector(OS);
1993 MatcherNode *Matcher = 0;
1994 // Walk the patterns backwards, building a matcher for each and adding it to
1995 // the matcher for the whole target.
1996 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1997 E = CGP.ptm_end(); I != E;) {
1998 const PatternToMatch &Pattern = *--E;
1999 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
2004 Matcher = new PushMatcherNode(N, Matcher);
2007 // OptimizeMatcher(Matcher);
2008 EmitMatcherTable(Matcher, OS);