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 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
52 static bool NodeIsComplexPattern(TreePatternNode *N) {
53 return (N->isLeaf() &&
54 dynamic_cast<DefInit*>(N->getLeafValue()) &&
55 static_cast<DefInit*>(N->getLeafValue())->getDef()->
56 isSubClassOf("ComplexPattern"));
60 /// getPatternSize - Return the 'size' of this pattern. We want to match large
61 /// patterns before small ones. This is used to determine the size of a
63 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
64 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
65 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
66 P->getExtTypeNum(0) == MVT::isVoid ||
67 P->getExtTypeNum(0) == MVT::Flag ||
68 P->getExtTypeNum(0) == MVT::iPTR ||
69 P->getExtTypeNum(0) == MVT::iPTRAny) &&
70 "Not a valid pattern node to size!");
71 unsigned Size = 3; // The node itself.
72 // If the root node is a ConstantSDNode, increases its size.
73 // e.g. (set R32:$dst, 0).
74 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
77 // FIXME: This is a hack to statically increase the priority of patterns
78 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
79 // Later we can allow complexity / cost for each pattern to be (optionally)
80 // specified. To get best possible pattern match we'll need to dynamically
81 // calculate the complexity of all patterns a dag can potentially map to.
82 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
84 Size += AM->getNumOperands() * 3;
86 // If this node has some predicate function that must match, it adds to the
87 // complexity of this node.
88 if (!P->getPredicateFns().empty())
91 // Count children in the count if they are also nodes.
92 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
93 TreePatternNode *Child = P->getChild(i);
94 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
95 Size += getPatternSize(Child, CGP);
96 else if (Child->isLeaf()) {
97 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
98 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
99 else if (NodeIsComplexPattern(Child))
100 Size += getPatternSize(Child, CGP);
101 else if (!Child->getPredicateFns().empty())
109 /// getResultPatternCost - Compute the number of instructions for this pattern.
110 /// This is a temporary hack. We should really include the instruction
111 /// latencies in this calculation.
112 static unsigned getResultPatternCost(TreePatternNode *P,
113 CodeGenDAGPatterns &CGP) {
114 if (P->isLeaf()) return 0;
117 Record *Op = P->getOperator();
118 if (Op->isSubClassOf("Instruction")) {
120 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
121 if (II.usesCustomInserter)
124 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
125 Cost += getResultPatternCost(P->getChild(i), CGP);
129 /// getResultPatternCodeSize - Compute the code size of instructions for this
131 static unsigned getResultPatternSize(TreePatternNode *P,
132 CodeGenDAGPatterns &CGP) {
133 if (P->isLeaf()) return 0;
136 Record *Op = P->getOperator();
137 if (Op->isSubClassOf("Instruction")) {
138 Cost += Op->getValueAsInt("CodeSize");
140 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
141 Cost += getResultPatternSize(P->getChild(i), CGP);
145 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
146 // In particular, we want to match maximal patterns first and lowest cost within
147 // a particular complexity first.
148 struct PatternSortingPredicate {
149 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
150 CodeGenDAGPatterns &CGP;
152 typedef std::pair<unsigned, std::string> CodeLine;
153 typedef std::vector<CodeLine> CodeList;
154 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
156 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
157 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
158 const PatternToMatch *LHS = LHSPair.first;
159 const PatternToMatch *RHS = RHSPair.first;
161 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
162 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
163 LHSSize += LHS->getAddedComplexity();
164 RHSSize += RHS->getAddedComplexity();
165 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
166 if (LHSSize < RHSSize) return false;
168 // If the patterns have equal complexity, compare generated instruction cost
169 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
170 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
171 if (LHSCost < RHSCost) return true;
172 if (LHSCost > RHSCost) return false;
174 return getResultPatternSize(LHS->getDstPattern(), CGP) <
175 getResultPatternSize(RHS->getDstPattern(), CGP);
179 /// getRegisterValueType - Look up and return the ValueType of the specified
180 /// register. If the register is a member of multiple register classes which
181 /// have different associated types, return MVT::Other.
182 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
183 bool FoundRC = false;
184 MVT::SimpleValueType VT = MVT::Other;
185 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
186 std::vector<CodeGenRegisterClass>::const_iterator RC;
187 std::vector<Record*>::const_iterator Element;
189 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
190 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
191 if (Element != (*RC).Elements.end()) {
194 VT = (*RC).getValueTypeNum(0);
197 if (VT != (*RC).getValueTypeNum(0)) {
198 // Types of the RC's do not agree. Return MVT::Other. The
199 // target is responsible for handling this.
208 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
209 return CGP.getSDNodeInfo(Op).getEnumName();
212 //===----------------------------------------------------------------------===//
213 // Node Transformation emitter implementation.
215 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
216 // Walk the pattern fragments, adding them to a map, which sorts them by
218 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
219 NXsByNameTy NXsByName;
221 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
223 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
225 OS << "\n// Node transformations.\n";
227 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
229 Record *SDNode = I->second.first;
230 std::string Code = I->second.second;
232 if (Code.empty()) continue; // Empty code? Skip it.
234 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
235 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
237 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
239 if (ClassName != "SDNode")
240 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
241 OS << Code << "\n}\n";
245 //===----------------------------------------------------------------------===//
246 // Predicate emitter implementation.
249 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
250 OS << "\n// Predicate functions.\n";
252 // Walk the pattern fragments, adding them to a map, which sorts them by
254 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
255 PFsByNameTy PFsByName;
257 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
259 PFsByName.insert(std::make_pair(I->first->getName(), *I));
262 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
264 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
265 TreePattern *P = I->second.second;
267 // If there is a code init for this fragment, emit the predicate code.
268 std::string Code = PatFragRecord->getValueAsCode("Predicate");
269 if (Code.empty()) continue;
271 if (P->getOnlyTree()->isLeaf())
272 OS << "inline bool Predicate_" << PatFragRecord->getName()
273 << "(SDNode *N) {\n";
275 std::string ClassName =
276 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
277 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
279 OS << "inline bool Predicate_" << PatFragRecord->getName()
280 << "(SDNode *" << C2 << ") {\n";
281 if (ClassName != "SDNode")
282 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
284 OS << Code << "\n}\n";
291 //===----------------------------------------------------------------------===//
292 // PatternCodeEmitter implementation.
294 class PatternCodeEmitter {
296 CodeGenDAGPatterns &CGP;
299 std::string PredicateCheck;
302 // Instruction selector pattern.
303 TreePatternNode *Pattern;
304 // Matched instruction.
305 TreePatternNode *Instruction;
307 // Node to name mapping
308 std::map<std::string, std::string> VariableMap;
309 // Node to operator mapping
310 std::map<std::string, Record*> OperatorMap;
311 // Name of the folded node which produces a flag.
312 std::pair<std::string, unsigned> FoldedFlag;
313 // Names of all the folded nodes which produce chains.
314 std::vector<std::pair<std::string, unsigned> > FoldedChains;
315 // Original input chain(s).
316 std::vector<std::pair<std::string, std::string> > OrigChains;
317 std::set<std::string> Duplicates;
319 /// LSI - Load/Store information.
320 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
321 /// for each memory access. This facilitates the use of AliasAnalysis in
323 std::vector<std::string> LSI;
325 /// GeneratedCode - This is the buffer that we emit code to. The first int
326 /// indicates whether this is an exit predicate (something that should be
327 /// tested, and if true, the match fails) [when 1], or normal code to emit
328 /// [when 0], or initialization code to emit [when 2].
329 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
330 /// GeneratedDecl - This is the set of all SDValue declarations needed for
331 /// the set of patterns for each top-level opcode.
332 std::set<std::string> &GeneratedDecl;
333 /// TargetOpcodes - The target specific opcodes used by the resulting
335 std::vector<std::string> &TargetOpcodes;
336 std::vector<std::string> &TargetVTs;
337 /// OutputIsVariadic - Records whether the instruction output pattern uses
338 /// variable_ops. This requires that the Emit function be passed an
339 /// additional argument to indicate where the input varargs operands
341 bool &OutputIsVariadic;
342 /// NumInputRootOps - Records the number of operands the root node of the
343 /// input pattern has. This information is used in the generated code to
344 /// pass to Emit functions when variable_ops processing is needed.
345 unsigned &NumInputRootOps;
347 std::string ChainName;
352 void emitCheck(const std::string &S) {
354 GeneratedCode.push_back(std::make_pair(1, S));
356 void emitCode(const std::string &S) {
358 GeneratedCode.push_back(std::make_pair(0, S));
360 void emitInit(const std::string &S) {
362 GeneratedCode.push_back(std::make_pair(2, S));
364 void emitDecl(const std::string &S) {
365 assert(!S.empty() && "Invalid declaration");
366 GeneratedDecl.insert(S);
368 void emitOpcode(const std::string &Opc) {
369 TargetOpcodes.push_back(Opc);
372 void emitVT(const std::string &VT) {
373 TargetVTs.push_back(VT);
377 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
378 TreePatternNode *pattern, TreePatternNode *instr,
379 std::vector<std::pair<unsigned, std::string> > &gc,
380 std::set<std::string> &gd,
381 std::vector<std::string> &to,
382 std::vector<std::string> &tv,
385 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
386 GeneratedCode(gc), GeneratedDecl(gd),
387 TargetOpcodes(to), TargetVTs(tv),
388 OutputIsVariadic(oiv), NumInputRootOps(niro),
389 TmpNo(0), OpcNo(0), VTNo(0) {}
391 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
392 /// if the match fails. At this point, we already know that the opcode for N
393 /// matches, and the SDNode for the result has the RootName specified name.
394 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
395 const std::string &RootName, const std::string &ChainSuffix,
398 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
399 const std::string &RootName,
400 const std::string &ChainSuffix, bool &FoundChain);
402 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
403 /// we actually have to build a DAG!
404 std::vector<std::string>
405 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
406 bool InFlagDecled, bool ResNodeDecled,
407 bool LikeLeaf = false, bool isRoot = false);
409 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
410 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
411 /// 'Pat' may be missing types. If we find an unresolved type to add a check
412 /// for, this returns true otherwise false if Pat has all types.
413 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
414 const std::string &Prefix, bool isRoot = false) {
416 if (Pat->getExtTypes() != Other->getExtTypes()) {
417 // Move a type over from 'other' to 'pat'.
418 Pat->setTypes(Other->getExtTypes());
419 // The top level node type is checked outside of the select function.
421 emitCheck(Prefix + ".getValueType() == " +
422 getName(Pat->getTypeNum(0)));
426 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
427 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
428 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
429 Prefix + utostr(OpNo)))
435 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
437 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
438 bool &ChainEmitted, bool &InFlagDecled,
439 bool &ResNodeDecled, bool isRoot = false) {
440 const CodeGenTarget &T = CGP.getTargetInfo();
441 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
442 bool HasInFlag = N->NodeHasProperty(SDNPInFlag, CGP);
443 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
444 TreePatternNode *Child = N->getChild(i);
445 if (!Child->isLeaf()) {
446 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
447 InFlagDecled, ResNodeDecled);
449 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
450 if (!Child->getName().empty()) {
451 std::string Name = RootName + utostr(OpNo);
452 if (Duplicates.find(Name) != Duplicates.end())
453 // A duplicate! Do not emit a copy for this node.
457 Record *RR = DI->getDef();
458 if (RR->isSubClassOf("Register")) {
459 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
460 if (RVT == MVT::Flag) {
462 emitCode("SDValue InFlag = " +
463 getValueName(RootName + utostr(OpNo)) + ";");
466 emitCode("InFlag = " +
467 getValueName(RootName + utostr(OpNo)) + ";");
470 emitCode("SDValue Chain = CurDAG->getEntryNode();");
475 emitCode("SDValue InFlag(0, 0);");
478 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
479 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
480 ", " + getNodeName(RootName) + "->getDebugLoc()" +
481 ", " + getQualifiedName(RR) +
482 ", " + getValueName(RootName + utostr(OpNo)) +
483 ", InFlag).getNode();");
484 ResNodeDecled = true;
485 emitCode(ChainName + " = SDValue(ResNode, 0);");
486 emitCode("InFlag = SDValue(ResNode, 1);");
495 emitCode("SDValue InFlag = " + getNodeName(RootName) +
496 "->getOperand(" + utostr(OpNo) + ");");
499 emitCode("InFlag = " + getNodeName(RootName) +
500 "->getOperand(" + utostr(OpNo) + ");");
506 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
507 /// if the match fails. At this point, we already know that the opcode for N
508 /// matches, and the SDNode for the result has the RootName specified name.
509 void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
510 const std::string &RootName,
511 const std::string &ChainSuffix,
514 // Save loads/stores matched by a pattern.
515 if (!N->isLeaf() && N->getName().empty()) {
516 if (N->NodeHasProperty(SDNPMemOperand, CGP))
517 LSI.push_back(getNodeName(RootName));
520 bool isRoot = (P == NULL);
521 // Emit instruction predicates. Each predicate is just a string for now.
523 // Record input varargs info.
524 NumInputRootOps = N->getNumChildren();
525 emitCheck(PredicateCheck);
529 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
530 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
531 ")->getSExtValue() == INT64_C(" +
532 itostr(II->getValue()) + ")");
534 } else if (!NodeIsComplexPattern(N)) {
535 assert(0 && "Cannot match this as a leaf value!");
540 // If this node has a name associated with it, capture it in VariableMap. If
541 // we already saw this in the pattern, emit code to verify dagness.
542 if (!N->getName().empty()) {
543 std::string &VarMapEntry = VariableMap[N->getName()];
544 if (VarMapEntry.empty()) {
545 VarMapEntry = RootName;
547 // If we get here, this is a second reference to a specific name. Since
548 // we already have checked that the first reference is valid, we don't
549 // have to recursively match it, just check that it's the same as the
550 // previously named thing.
551 emitCheck(VarMapEntry + " == " + RootName);
556 OperatorMap[N->getName()] = N->getOperator();
560 // Emit code to load the child nodes and match their contents recursively.
562 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
563 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
568 // Check if it's profitable to fold the node. e.g. Check for multiple uses
570 std::string ParentName(RootName.begin(), RootName.end()-1);
571 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
572 ", " + getNodeName(ParentName) + ", N)");
574 // If the immediate use can somehow reach this node through another
575 // path, then can't fold it either or it will create a cycle.
576 // e.g. In the following diagram, XX can reach ld through YY. If
577 // ld is folded into XX, then YY is both a predecessor and a successor
588 // We know we need the check if N's parent is not the root.
589 bool NeedCheck = P != Pattern;
591 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
593 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
594 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
595 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
596 PInfo.getNumOperands() > 1 ||
597 PInfo.hasProperty(SDNPHasChain) ||
598 PInfo.hasProperty(SDNPInFlag) ||
599 PInfo.hasProperty(SDNPOptInFlag);
603 emitCheck("IsLegalToFold(" + getValueName(RootName) +
604 ", " + getNodeName(ParentName) + ", N)");
611 emitCheck("(" + ChainName + ".getNode() == " +
612 getNodeName(RootName) + " || "
613 "IsChainCompatible(" + ChainName + ".getNode(), " +
614 getNodeName(RootName) + "))");
615 OrigChains.push_back(std::make_pair(ChainName,
616 getValueName(RootName)));
619 ChainName = "Chain" + ChainSuffix;
620 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
625 // If there are node predicates for this, emit the calls.
626 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
627 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
629 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
630 // a constant without a predicate fn that has more that one bit set, handle
631 // this as a special case. This is usually for targets that have special
632 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
633 // handling stuff). Using these instructions is often far more efficient
634 // than materializing the constant. Unfortunately, both the instcombiner
635 // and the dag combiner can often infer that bits are dead, and thus drop
636 // them from the mask in the dag. For example, it might turn 'AND X, 255'
637 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
640 (N->getOperator()->getName() == "and" ||
641 N->getOperator()->getName() == "or") &&
642 N->getChild(1)->isLeaf() &&
643 N->getChild(1)->getPredicateFns().empty()) {
644 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
645 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
646 emitInit("SDValue " + RootName + "0" + " = " +
647 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
648 emitInit("SDValue " + RootName + "1" + " = " +
649 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
651 unsigned NTmp = TmpNo++;
652 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
653 " = dyn_cast<ConstantSDNode>(" +
654 getNodeName(RootName + "1") + ");");
655 emitCheck("Tmp" + utostr(NTmp));
656 const char *MaskPredicate = N->getOperator()->getName() == "or"
657 ? "CheckOrMask(" : "CheckAndMask(";
658 emitCheck(MaskPredicate + getValueName(RootName + "0") +
659 ", Tmp" + utostr(NTmp) +
660 ", INT64_C(" + itostr(II->getValue()) + "))");
662 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
663 ChainSuffix + utostr(0), FoundChain);
669 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
670 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
671 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
673 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
674 ChainSuffix + utostr(OpNo), FoundChain);
677 // Handle cases when root is a complex pattern.
678 const ComplexPattern *CP;
679 if (isRoot && N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
680 std::string Fn = CP->getSelectFunc();
681 unsigned NumOps = CP->getNumOperands();
682 for (unsigned i = 0; i < NumOps; ++i) {
683 emitDecl("CPTmp" + RootName + "_" + utostr(i));
684 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
686 if (CP->hasProperty(SDNPHasChain)) {
687 emitDecl("CPInChain");
688 emitDecl("Chain" + ChainSuffix);
689 emitCode("SDValue CPInChain;");
690 emitCode("SDValue Chain" + ChainSuffix + ";");
693 std::string Code = Fn + "(" +
694 getNodeName(RootName) + ", " +
695 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);
730 // If this child has a name associated with it, capture it in VarMap. If
731 // we already saw this in the pattern, emit code to verify dagness.
732 if (!Child->getName().empty()) {
733 std::string &VarMapEntry = VariableMap[Child->getName()];
734 if (VarMapEntry.empty()) {
735 VarMapEntry = getValueName(RootName);
737 // If we get here, this is a second reference to a specific name.
738 // Since we already have checked that the first reference is valid,
739 // we don't have to recursively match it, just check that it's the
740 // same as the previously named thing.
741 emitCheck(VarMapEntry + " == " + getValueName(RootName));
742 Duplicates.insert(getValueName(RootName));
747 // Handle leaves of various types.
748 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
749 Record *LeafRec = DI->getDef();
750 if (LeafRec->isSubClassOf("RegisterClass") ||
751 LeafRec->isSubClassOf("PointerLikeRegClass")) {
752 // Handle register references. Nothing to do here.
753 } else if (LeafRec->isSubClassOf("Register")) {
754 // Handle register references.
755 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
756 // Handle complex pattern.
757 const ComplexPattern *CP = Child->getComplexPatternInfo(CGP);
758 std::string Fn = CP->getSelectFunc();
759 unsigned NumOps = CP->getNumOperands();
760 for (unsigned i = 0; i < NumOps; ++i) {
761 emitDecl("CPTmp" + RootName + "_" + utostr(i));
762 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
764 if (CP->hasProperty(SDNPHasChain)) {
765 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
766 FoldedChains.push_back(std::make_pair("CPInChain",
767 PInfo.getNumResults()));
768 ChainName = "Chain" + ChainSuffix;
769 emitDecl("CPInChain");
771 emitCode("SDValue CPInChain;");
772 emitCode("SDValue " + ChainName + ";");
775 std::string Code = Fn + "(N, ";
776 if (CP->hasProperty(SDNPHasChain)) {
777 std::string ParentName(RootName.begin(), RootName.end()-1);
778 Code += getValueName(ParentName) + ", ";
780 Code += getValueName(RootName);
781 for (unsigned i = 0; i < NumOps; i++)
782 Code += ", CPTmp" + RootName + "_" + utostr(i);
783 if (CP->hasProperty(SDNPHasChain))
784 Code += ", CPInChain, Chain" + ChainSuffix;
785 emitCheck(Code + ")");
786 } else if (LeafRec->getName() == "srcvalue") {
787 // Place holder for SRCVALUE nodes. Nothing to do here.
788 } else if (LeafRec->isSubClassOf("ValueType")) {
789 // Make sure this is the specified value type.
790 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
791 ")->getVT() == MVT::" + LeafRec->getName());
792 } else if (LeafRec->isSubClassOf("CondCode")) {
793 // Make sure this is the specified cond code.
794 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
795 ")->get() == ISD::" + LeafRec->getName());
801 assert(0 && "Unknown leaf type!");
804 // If there are node predicates for this, emit the calls.
805 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
806 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
808 } else if (IntInit *II =
809 dynamic_cast<IntInit*>(Child->getLeafValue())) {
810 unsigned NTmp = TmpNo++;
811 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
812 " = dyn_cast<ConstantSDNode>("+
813 getNodeName(RootName) + ");");
814 emitCheck("Tmp" + utostr(NTmp));
815 unsigned CTmp = TmpNo++;
816 emitCode("int64_t CN"+ utostr(CTmp) +
817 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
818 emitCheck("CN" + utostr(CTmp) + " == "
819 "INT64_C(" +itostr(II->getValue()) + ")");
824 assert(0 && "Unknown leaf type!");
829 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
830 /// we actually have to build a DAG!
831 std::vector<std::string>
832 PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
833 std::vector<Record*> DstRegs,
834 bool InFlagDecled, bool ResNodeDecled,
835 bool LikeLeaf, bool isRoot) {
836 // List of arguments of getMachineNode() or SelectNodeTo().
837 std::vector<std::string> NodeOps;
838 // This is something selected from the pattern we matched.
839 if (!N->getName().empty()) {
840 const std::string &VarName = N->getName();
841 std::string Val = VariableMap[VarName];
842 bool ModifiedVal = false;
844 errs() << "Variable '" << VarName << " referenced but not defined "
845 << "and not caught earlier!\n";
848 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
849 // Already selected this operand, just return the tmpval.
850 NodeOps.push_back(getValueName(Val));
854 const ComplexPattern *CP;
855 unsigned ResNo = TmpNo++;
856 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
857 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
858 std::string CastType;
859 std::string TmpVar = "Tmp" + utostr(ResNo);
860 switch (N->getTypeNum(0)) {
862 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
863 << " type as an immediate constant. Aborting\n";
865 case MVT::i1: CastType = "bool"; break;
866 case MVT::i8: CastType = "unsigned char"; break;
867 case MVT::i16: CastType = "unsigned short"; break;
868 case MVT::i32: CastType = "unsigned"; break;
869 case MVT::i64: CastType = "uint64_t"; break;
871 emitCode("SDValue " + TmpVar +
872 " = CurDAG->getTargetConstant(((" + CastType +
873 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
874 getEnumName(N->getTypeNum(0)) + ");");
875 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
876 // value if used multiple times by this pattern result.
879 NodeOps.push_back(getValueName(Val));
880 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
881 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
882 std::string TmpVar = "Tmp" + utostr(ResNo);
883 emitCode("SDValue " + TmpVar +
884 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
885 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
886 Val + ")->getValueType(0));");
887 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
888 // value if used multiple times by this pattern result.
891 NodeOps.push_back(getValueName(Val));
892 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
893 Record *Op = OperatorMap[N->getName()];
894 // Transform ExternalSymbol to TargetExternalSymbol
895 if (Op && Op->getName() == "externalsym") {
896 std::string TmpVar = "Tmp"+utostr(ResNo);
897 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
898 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
899 Val + ")->getSymbol(), " +
900 getEnumName(N->getTypeNum(0)) + ");");
901 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
902 // this value if used multiple times by this pattern result.
906 NodeOps.push_back(getValueName(Val));
907 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
908 || N->getOperator()->getName() == "tglobaltlsaddr")) {
909 Record *Op = OperatorMap[N->getName()];
910 // Transform GlobalAddress to TargetGlobalAddress
911 if (Op && (Op->getName() == "globaladdr" ||
912 Op->getName() == "globaltlsaddr")) {
913 std::string TmpVar = "Tmp" + utostr(ResNo);
914 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
915 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
916 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
918 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
919 // this value if used multiple times by this pattern result.
923 NodeOps.push_back(getValueName(Val));
924 } else if (!N->isLeaf()
925 && (N->getOperator()->getName() == "texternalsym" ||
926 N->getOperator()->getName() == "tconstpool")) {
927 // Do not rewrite the variable name, since we don't generate a new
929 NodeOps.push_back(getValueName(Val));
930 } else if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
931 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
932 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
935 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
936 // node even if it isn't one. Don't select it.
938 if (isRoot && N->isLeaf()) {
939 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
940 emitCode("return NULL;");
943 NodeOps.push_back(getValueName(Val));
947 VariableMap[VarName] = Val;
951 // If this is an explicit register reference, handle it.
952 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
953 unsigned ResNo = TmpNo++;
954 if (DI->getDef()->isSubClassOf("Register")) {
955 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
956 getQualifiedName(DI->getDef()) + ", " +
957 getEnumName(N->getTypeNum(0)) + ");");
958 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
960 } else if (DI->getDef()->getName() == "zero_reg") {
961 emitCode("SDValue Tmp" + utostr(ResNo) +
962 " = CurDAG->getRegister(0, " +
963 getEnumName(N->getTypeNum(0)) + ");");
964 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
966 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
967 // Handle a reference to a register class. This is used
968 // in COPY_TO_SUBREG instructions.
969 emitCode("SDValue Tmp" + utostr(ResNo) +
970 " = CurDAG->getTargetConstant(" +
971 getQualifiedName(DI->getDef()) + "RegClassID, " +
973 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
976 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
977 unsigned ResNo = TmpNo++;
978 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
979 emitCode("SDValue Tmp" + utostr(ResNo) +
980 " = CurDAG->getTargetConstant(0x" +
981 utohexstr((uint64_t) II->getValue()) +
982 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
983 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
990 assert(0 && "Unknown leaf type!");
994 Record *Op = N->getOperator();
995 if (Op->isSubClassOf("Instruction")) {
996 const CodeGenTarget &CGT = CGP.getTargetInfo();
997 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
998 const DAGInstruction &Inst = CGP.getInstruction(Op);
999 const TreePattern *InstPat = Inst.getPattern();
1000 // FIXME: Assume actual pattern comes before "implicit".
1001 TreePatternNode *InstPatNode =
1002 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
1003 : (InstPat ? InstPat->getTree(0) : NULL);
1004 if (InstPatNode && !InstPatNode->isLeaf() &&
1005 InstPatNode->getOperator()->getName() == "set") {
1006 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
1008 bool IsVariadic = isRoot && II.isVariadic;
1009 // FIXME: fix how we deal with physical register operands.
1010 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1011 bool HasImpResults = isRoot && DstRegs.size() > 0;
1012 bool NodeHasOptInFlag = isRoot &&
1013 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
1014 bool NodeHasInFlag = isRoot &&
1015 Pattern->TreeHasProperty(SDNPInFlag, CGP);
1016 bool NodeHasOutFlag = isRoot &&
1017 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
1018 bool NodeHasChain = InstPatNode &&
1019 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
1020 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
1021 unsigned NumResults = Inst.getNumResults();
1022 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1024 // Record output varargs info.
1025 OutputIsVariadic = IsVariadic;
1027 if (NodeHasOptInFlag) {
1028 emitCode("bool HasInFlag = "
1029 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1033 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1035 // How many results is this pattern expected to produce?
1036 unsigned NumPatResults = 0;
1037 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1038 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1039 if (VT != MVT::isVoid && VT != MVT::Flag)
1043 if (OrigChains.size() > 0) {
1044 // The original input chain is being ignored. If it is not just
1045 // pointing to the op that's being folded, we should create a
1046 // TokenFactor with it and the chain of the folded op as the new chain.
1047 // We could potentially be doing multiple levels of folding, in that
1048 // case, the TokenFactor can have more operands.
1049 emitCode("SmallVector<SDValue, 8> InChains;");
1050 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1051 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1052 OrigChains[i].second + ".getNode()) {");
1053 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1056 emitCode("InChains.push_back(" + ChainName + ");");
1057 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1058 "N->getDebugLoc(), MVT::Other, "
1059 "&InChains[0], InChains.size());");
1061 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1062 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1066 // Loop over all of the operands of the instruction pattern, emitting code
1067 // to fill them all in. The node 'N' usually has number children equal to
1068 // the number of input operands of the instruction. However, in cases
1069 // where there are predicate operands for an instruction, we need to fill
1070 // in the 'execute always' values. Match up the node operands to the
1071 // instruction operands to do this.
1072 std::vector<std::string> AllOps;
1073 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1074 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1075 std::vector<std::string> Ops;
1077 // Determine what to emit for this operand.
1078 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1079 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1080 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1081 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1082 // This is a predicate or optional def operand; emit the
1083 // 'default ops' operands.
1084 const DAGDefaultOperand &DefaultOp =
1085 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1086 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1087 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1088 InFlagDecled, ResNodeDecled);
1089 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1092 // Otherwise this is a normal operand or a predicate operand without
1093 // 'execute always'; emit it.
1094 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1095 InFlagDecled, ResNodeDecled);
1096 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1101 // Emit all the chain and CopyToReg stuff.
1102 bool ChainEmitted = NodeHasChain;
1103 if (NodeHasInFlag || HasImpInputs)
1104 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1105 InFlagDecled, ResNodeDecled, true);
1106 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1107 if (!InFlagDecled) {
1108 emitCode("SDValue InFlag(0, 0);");
1109 InFlagDecled = true;
1111 if (NodeHasOptInFlag) {
1112 emitCode("if (HasInFlag) {");
1113 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1118 unsigned ResNo = TmpNo++;
1120 unsigned OpsNo = OpcNo;
1121 std::string CodePrefix;
1122 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1123 std::deque<std::string> After;
1124 std::string NodeName;
1126 NodeName = "Tmp" + utostr(ResNo);
1127 CodePrefix = "SDValue " + NodeName + "(";
1129 NodeName = "ResNode";
1130 if (!ResNodeDecled) {
1131 CodePrefix = "SDNode *" + NodeName + " = ";
1132 ResNodeDecled = true;
1134 CodePrefix = NodeName + " = ";
1137 std::string Code = "Opc" + utostr(OpcNo);
1139 if (!isRoot || (InputHasChain && !NodeHasChain))
1140 // For call to "getMachineNode()".
1141 Code += ", N->getDebugLoc()";
1143 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1145 // Output order: results, chain, flags
1147 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1148 Code += ", VT" + utostr(VTNo);
1149 emitVT(getEnumName(N->getTypeNum(0)));
1151 // Add types for implicit results in physical registers, scheduler will
1152 // care of adding copyfromreg nodes.
1153 for (unsigned i = 0; i < NumDstRegs; i++) {
1154 Record *RR = DstRegs[i];
1155 if (RR->isSubClassOf("Register")) {
1156 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1157 Code += ", " + getEnumName(RVT);
1161 Code += ", MVT::Other";
1163 Code += ", MVT::Flag";
1167 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1168 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1171 // Figure out whether any operands at the end of the op list are not
1172 // part of the variable section.
1173 std::string EndAdjust;
1174 if (NodeHasInFlag || HasImpInputs)
1175 EndAdjust = "-1"; // Always has one flag.
1176 else if (NodeHasOptInFlag)
1177 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1179 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1180 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1182 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1186 // Populate MemRefs with entries for each memory accesses covered by
1188 if (isRoot && !LSI.empty()) {
1189 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1190 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1191 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1192 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1193 emitCode(MemRefs + "[" + utostr(i) + "] = "
1194 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1195 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1196 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1202 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1204 AllOps.push_back(ChainName);
1208 if (NodeHasInFlag || HasImpInputs)
1209 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1210 else if (NodeHasOptInFlag) {
1211 emitCode("if (HasInFlag)");
1212 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1214 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1216 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1217 AllOps.push_back("InFlag");
1219 unsigned NumOps = AllOps.size();
1221 if (!NodeHasOptInFlag && NumOps < 4) {
1222 for (unsigned i = 0; i != NumOps; ++i)
1223 Code += ", " + AllOps[i];
1225 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1226 for (unsigned i = 0; i != NumOps; ++i) {
1227 OpsCode += AllOps[i];
1231 emitCode(OpsCode + " };");
1232 Code += ", Ops" + utostr(OpsNo) + ", ";
1233 if (NodeHasOptInFlag) {
1234 Code += "HasInFlag ? ";
1235 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1237 Code += utostr(NumOps);
1244 std::vector<std::string> ReplaceFroms;
1245 std::vector<std::string> ReplaceTos;
1247 NodeOps.push_back("Tmp" + utostr(ResNo));
1250 if (NodeHasOutFlag) {
1251 if (!InFlagDecled) {
1252 After.push_back("SDValue InFlag(ResNode, " +
1253 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1255 InFlagDecled = true;
1257 After.push_back("InFlag = SDValue(ResNode, " +
1258 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1262 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1263 ReplaceFroms.push_back("SDValue(" +
1264 FoldedChains[j].first + ".getNode(), " +
1265 utostr(FoldedChains[j].second) +
1267 ReplaceTos.push_back("SDValue(ResNode, " +
1268 utostr(NumResults+NumDstRegs) + ")");
1271 if (NodeHasOutFlag) {
1272 if (FoldedFlag.first != "") {
1273 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1274 utostr(FoldedFlag.second) + ")");
1275 ReplaceTos.push_back("InFlag");
1277 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
1278 ReplaceFroms.push_back("SDValue(N, " +
1279 utostr(NumPatResults + (unsigned)InputHasChain)
1281 ReplaceTos.push_back("InFlag");
1285 if (!ReplaceFroms.empty() && InputHasChain) {
1286 ReplaceFroms.push_back("SDValue(N, " +
1287 utostr(NumPatResults) + ")");
1288 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1289 ChainName + ".getResNo()" + ")");
1290 ChainAssignmentNeeded |= NodeHasChain;
1293 // User does not expect the instruction would produce a chain!
1294 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1296 } else if (InputHasChain && !NodeHasChain) {
1297 // One of the inner node produces a chain.
1298 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1299 ReplaceFroms.push_back("SDValue(N, " +
1300 utostr(NumPatResults) + ")");
1301 ReplaceTos.push_back(ChainName);
1305 if (ChainAssignmentNeeded) {
1306 // Remember which op produces the chain.
1307 std::string ChainAssign;
1309 ChainAssign = ChainName + " = SDValue(" + NodeName +
1310 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1312 ChainAssign = ChainName + " = SDValue(" + NodeName +
1313 ", " + utostr(NumResults+NumDstRegs) + ");";
1315 After.push_front(ChainAssign);
1318 if (ReplaceFroms.size() == 1) {
1319 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1320 ReplaceTos[0] + ");");
1321 } else if (!ReplaceFroms.empty()) {
1322 After.push_back("const SDValue Froms[] = {");
1323 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1324 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1325 After.push_back("};");
1326 After.push_back("const SDValue Tos[] = {");
1327 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1328 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1329 After.push_back("};");
1330 After.push_back("ReplaceUses(Froms, Tos, " +
1331 itostr(ReplaceFroms.size()) + ");");
1334 // We prefer to use SelectNodeTo since it avoids allocation when
1335 // possible and it avoids CSE map recalculation for the node's
1336 // users, however it's tricky to use in a non-root context.
1338 // We also don't use SelectNodeTo if the pattern replacement is being
1339 // used to jettison a chain result, since morphing the node in place
1340 // would leave users of the chain dangling.
1342 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1343 Code = "CurDAG->getMachineNode(" + Code;
1345 Code = "CurDAG->SelectNodeTo(N, " + Code;
1349 CodePrefix = "return ";
1351 After.push_back("return ResNode;");
1354 emitCode(CodePrefix + Code + ");");
1358 emitCode("CurDAG->setSubgraphColor(" +
1359 NodeName +".getNode(), \"yellow\");");
1360 emitCode("CurDAG->setSubgraphColor(" +
1361 NodeName +".getNode(), \"black\");");
1363 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1364 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1368 for (unsigned i = 0, e = After.size(); i != e; ++i)
1373 if (Op->isSubClassOf("SDNodeXForm")) {
1374 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1375 // PatLeaf node - the operand may or may not be a leaf node. But it should
1377 std::vector<std::string> Ops =
1378 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1379 ResNodeDecled, true);
1380 unsigned ResNo = TmpNo++;
1381 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1382 + "(" + Ops.back() + ".getNode());");
1383 NodeOps.push_back("Tmp" + utostr(ResNo));
1385 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1391 throw std::string("Unknown node in result pattern!");
1395 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1396 /// stream to match the pattern, and generate the code for the match if it
1397 /// succeeds. Returns true if the pattern is not guaranteed to match.
1398 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1399 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1400 std::set<std::string> &GeneratedDecl,
1401 std::vector<std::string> &TargetOpcodes,
1402 std::vector<std::string> &TargetVTs,
1403 bool &OutputIsVariadic,
1404 unsigned &NumInputRootOps) {
1405 OutputIsVariadic = false;
1406 NumInputRootOps = 0;
1408 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1409 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1410 GeneratedCode, GeneratedDecl,
1411 TargetOpcodes, TargetVTs,
1412 OutputIsVariadic, NumInputRootOps);
1414 // Emit the matcher, capturing named arguments in VariableMap.
1415 bool FoundChain = false;
1416 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1418 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1419 // diagnostics, which we know are impossible at this point.
1420 TreePattern &TP = *CGP.pf_begin()->second;
1422 // At this point, we know that we structurally match the pattern, but the
1423 // types of the nodes may not match. Figure out the fewest number of type
1424 // comparisons we need to emit. For example, if there is only one integer
1425 // type supported by a target, there should be no type comparisons at all for
1426 // integer patterns!
1428 // To figure out the fewest number of type checks needed, clone the pattern,
1429 // remove the types, then perform type inference on the pattern as a whole.
1430 // If there are unresolved types, emit an explicit check for those types,
1431 // apply the type to the tree, then rerun type inference. Iterate until all
1432 // types are resolved.
1434 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1435 Pat->RemoveAllTypes();
1438 // Resolve/propagate as many types as possible.
1440 bool MadeChange = true;
1442 MadeChange = Pat->ApplyTypeConstraints(TP,
1443 true/*Ignore reg constraints*/);
1445 assert(0 && "Error: could not find consistent types for something we"
1446 " already decided was ok!");
1450 // Insert a check for an unresolved type and add it to the tree. If we find
1451 // an unresolved type to add a check for, this returns true and we iterate,
1452 // otherwise we are done.
1453 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1455 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1456 false, false, false, true);
1460 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1461 /// a line causes any of them to be empty, remove them and return true when
1463 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1464 std::vector<std::pair<unsigned, std::string> > > >
1466 bool ErasedPatterns = false;
1467 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1468 Patterns[i].second.pop_back();
1469 if (Patterns[i].second.empty()) {
1470 Patterns.erase(Patterns.begin()+i);
1472 ErasedPatterns = true;
1475 return ErasedPatterns;
1478 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1479 /// code together between the patterns.
1480 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1481 std::vector<std::pair<unsigned, std::string> > > >
1482 &Patterns, unsigned Indent,
1484 typedef std::pair<unsigned, std::string> CodeLine;
1485 typedef std::vector<CodeLine> CodeList;
1486 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1488 if (Patterns.empty()) return;
1490 // Figure out how many patterns share the next code line. Explicitly copy
1491 // FirstCodeLine so that we don't invalidate a reference when changing
1493 const CodeLine FirstCodeLine = Patterns.back().second.back();
1494 unsigned LastMatch = Patterns.size()-1;
1495 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1498 // If not all patterns share this line, split the list into two pieces. The
1499 // first chunk will use this line, the second chunk won't.
1500 if (LastMatch != 0) {
1501 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1502 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1504 // FIXME: Emit braces?
1505 if (Shared.size() == 1) {
1506 const PatternToMatch &Pattern = *Shared.back().first;
1507 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1508 Pattern.getSrcPattern()->print(OS);
1509 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1510 Pattern.getDstPattern()->print(OS);
1512 unsigned AddedComplexity = Pattern.getAddedComplexity();
1513 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1514 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1516 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1518 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1520 if (FirstCodeLine.first != 1) {
1521 OS << std::string(Indent, ' ') << "{\n";
1524 EmitPatterns(Shared, Indent, OS);
1525 if (FirstCodeLine.first != 1) {
1527 OS << std::string(Indent, ' ') << "}\n";
1530 if (Other.size() == 1) {
1531 const PatternToMatch &Pattern = *Other.back().first;
1532 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1533 Pattern.getSrcPattern()->print(OS);
1534 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1535 Pattern.getDstPattern()->print(OS);
1537 unsigned AddedComplexity = Pattern.getAddedComplexity();
1538 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1539 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1541 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1543 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1545 EmitPatterns(Other, Indent, OS);
1549 // Remove this code from all of the patterns that share it.
1550 bool ErasedPatterns = EraseCodeLine(Patterns);
1552 bool isPredicate = FirstCodeLine.first == 1;
1554 // Otherwise, every pattern in the list has this line. Emit it.
1557 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1559 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1561 // If the next code line is another predicate, and if all of the pattern
1562 // in this group share the same next line, emit it inline now. Do this
1563 // until we run out of common predicates.
1564 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1565 // Check that all of the patterns in Patterns end with the same predicate.
1566 bool AllEndWithSamePredicate = true;
1567 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1568 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1569 AllEndWithSamePredicate = false;
1572 // If all of the predicates aren't the same, we can't share them.
1573 if (!AllEndWithSamePredicate) break;
1575 // Otherwise we can. Emit it shared now.
1576 OS << " &&\n" << std::string(Indent+4, ' ')
1577 << Patterns.back().second.back().second;
1578 ErasedPatterns = EraseCodeLine(Patterns);
1585 EmitPatterns(Patterns, Indent, OS);
1588 OS << std::string(Indent-2, ' ') << "}\n";
1591 static std::string getLegalCName(std::string OpName) {
1592 std::string::size_type pos = OpName.find("::");
1593 if (pos != std::string::npos)
1594 OpName.replace(pos, 2, "_");
1598 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1599 const CodeGenTarget &Target = CGP.getTargetInfo();
1601 // Get the namespace to insert instructions into.
1602 std::string InstNS = Target.getInstNamespace();
1603 if (!InstNS.empty()) InstNS += "::";
1605 // Group the patterns by their top-level opcodes.
1606 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1607 // All unique target node emission functions.
1608 std::map<std::string, unsigned> EmitFunctions;
1609 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1610 E = CGP.ptm_end(); I != E; ++I) {
1611 const PatternToMatch &Pattern = *I;
1612 TreePatternNode *Node = Pattern.getSrcPattern();
1613 if (!Node->isLeaf()) {
1614 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1615 push_back(&Pattern);
1617 const ComplexPattern *CP;
1618 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1619 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1620 push_back(&Pattern);
1621 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
1622 std::vector<Record*> OpNodes = CP->getRootNodes();
1623 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1624 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1625 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1629 errs() << "Unrecognized opcode '";
1631 errs() << "' on tree pattern '";
1632 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1638 // For each opcode, there might be multiple select functions, one per
1639 // ValueType of the node (or its first operand if it doesn't produce a
1640 // non-chain result.
1641 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1643 // Emit one Select_* method for each top-level opcode. We do this instead of
1644 // emitting one giant switch statement to support compilers where this will
1645 // result in the recursive functions taking less stack space.
1646 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1647 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1648 PBOI != E; ++PBOI) {
1649 const std::string &OpName = PBOI->first;
1650 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1651 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1653 // Split them into groups by type.
1654 std::map<MVT::SimpleValueType,
1655 std::vector<const PatternToMatch*> > PatternsByType;
1656 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1657 const PatternToMatch *Pat = PatternsOfOp[i];
1658 TreePatternNode *SrcPat = Pat->getSrcPattern();
1659 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1662 for (std::map<MVT::SimpleValueType,
1663 std::vector<const PatternToMatch*> >::iterator
1664 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1666 MVT::SimpleValueType OpVT = II->first;
1667 std::vector<const PatternToMatch*> &Patterns = II->second;
1668 typedef std::pair<unsigned, std::string> CodeLine;
1669 typedef std::vector<CodeLine> CodeList;
1670 typedef CodeList::iterator CodeListI;
1672 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1673 std::vector<std::vector<std::string> > PatternOpcodes;
1674 std::vector<std::vector<std::string> > PatternVTs;
1675 std::vector<std::set<std::string> > PatternDecls;
1676 std::vector<bool> OutputIsVariadicFlags;
1677 std::vector<unsigned> NumInputRootOpsCounts;
1678 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1679 CodeList GeneratedCode;
1680 std::set<std::string> GeneratedDecl;
1681 std::vector<std::string> TargetOpcodes;
1682 std::vector<std::string> TargetVTs;
1683 bool OutputIsVariadic;
1684 unsigned NumInputRootOps;
1685 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1686 TargetOpcodes, TargetVTs,
1687 OutputIsVariadic, NumInputRootOps);
1688 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1689 PatternDecls.push_back(GeneratedDecl);
1690 PatternOpcodes.push_back(TargetOpcodes);
1691 PatternVTs.push_back(TargetVTs);
1692 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1693 NumInputRootOpsCounts.push_back(NumInputRootOps);
1696 // Factor target node emission code (emitted by EmitResultCode) into
1697 // separate functions. Uniquing and share them among all instruction
1698 // selection routines.
1699 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1700 CodeList &GeneratedCode = CodeForPatterns[i].second;
1701 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1702 std::vector<std::string> &TargetVTs = PatternVTs[i];
1703 std::set<std::string> Decls = PatternDecls[i];
1704 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1705 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1706 std::vector<std::string> AddedInits;
1707 int CodeSize = (int)GeneratedCode.size();
1709 for (int j = CodeSize-1; j >= 0; --j) {
1710 if (LastPred == -1 && GeneratedCode[j].first == 1)
1712 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1713 AddedInits.push_back(GeneratedCode[j].second);
1716 std::string CalleeCode = "(SDNode *N";
1717 std::string CallerCode = "(N";
1718 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1719 CalleeCode += ", unsigned Opc" + utostr(j);
1720 CallerCode += ", " + TargetOpcodes[j];
1722 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1723 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
1724 CallerCode += ", " + TargetVTs[j];
1726 for (std::set<std::string>::iterator
1727 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1728 std::string Name = *I;
1729 CalleeCode += ", SDValue &" + Name;
1730 CallerCode += ", " + Name;
1733 if (OutputIsVariadic) {
1734 CalleeCode += ", unsigned NumInputRootOps";
1735 CallerCode += ", " + utostr(NumInputRootOps);
1739 CalleeCode += ") {\n";
1741 for (std::vector<std::string>::const_reverse_iterator
1742 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1743 CalleeCode += " " + *I + "\n";
1745 for (int j = LastPred+1; j < CodeSize; ++j)
1746 CalleeCode += " " + GeneratedCode[j].second + "\n";
1747 for (int j = LastPred+1; j < CodeSize; ++j)
1748 GeneratedCode.pop_back();
1749 CalleeCode += "}\n";
1751 // Uniquing the emission routines.
1752 unsigned EmitFuncNum;
1753 std::map<std::string, unsigned>::iterator EFI =
1754 EmitFunctions.find(CalleeCode);
1755 if (EFI != EmitFunctions.end()) {
1756 EmitFuncNum = EFI->second;
1758 EmitFuncNum = EmitFunctions.size();
1759 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1760 // Prevent emission routines from being inlined to reduce selection
1761 // routines stack frame sizes.
1762 OS << "DISABLE_INLINE ";
1763 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1766 // Replace the emission code within selection routines with calls to the
1767 // emission functions.
1769 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
1770 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1771 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1773 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1774 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1775 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1776 GeneratedCode.push_back(std::make_pair(0, "}"));
1777 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
1779 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1783 std::string OpVTStr;
1784 if (OpVT == MVT::iPTR) {
1786 } else if (OpVT == MVT::iPTRAny) {
1787 OpVTStr = "_iPTRAny";
1788 } else if (OpVT == MVT::isVoid) {
1789 // Nodes with a void result actually have a first result type of either
1790 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1791 // void to this case, we handle it specially here.
1793 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1795 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1796 OpcodeVTMap.find(OpName);
1797 if (OpVTI == OpcodeVTMap.end()) {
1798 std::vector<std::string> VTSet;
1799 VTSet.push_back(OpVTStr);
1800 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1802 OpVTI->second.push_back(OpVTStr);
1804 // We want to emit all of the matching code now. However, we want to emit
1805 // the matches in order of minimal cost. Sort the patterns so the least
1806 // cost one is at the start.
1807 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1808 PatternSortingPredicate(CGP));
1810 // Scan the code to see if all of the patterns are reachable and if it is
1811 // possible that the last one might not match.
1812 bool mightNotMatch = true;
1813 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1814 CodeList &GeneratedCode = CodeForPatterns[i].second;
1815 mightNotMatch = false;
1817 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1818 if (GeneratedCode[j].first == 1) { // predicate.
1819 mightNotMatch = true;
1824 // If this pattern definitely matches, and if it isn't the last one, the
1825 // patterns after it CANNOT ever match. Error out.
1826 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1827 errs() << "Pattern '";
1828 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1829 errs() << "' is impossible to select!\n";
1834 // Loop through and reverse all of the CodeList vectors, as we will be
1835 // accessing them from their logical front, but accessing the end of a
1836 // vector is more efficient.
1837 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1838 CodeList &GeneratedCode = CodeForPatterns[i].second;
1839 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1842 // Next, reverse the list of patterns itself for the same reason.
1843 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1845 OS << "SDNode *Select_" << getLegalCName(OpName)
1846 << OpVTStr << "(SDNode *N) {\n";
1848 // Emit all of the patterns now, grouped together to share code.
1849 EmitPatterns(CodeForPatterns, 2, OS);
1851 // If the last pattern has predicates (which could fail) emit code to
1852 // catch the case where nothing handles a pattern.
1853 if (mightNotMatch) {
1855 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1856 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1857 OpName != "ISD::INTRINSIC_VOID")
1858 OS << " CannotYetSelect(N);\n";
1860 OS << " CannotYetSelectIntrinsic(N);\n";
1862 OS << " return NULL;\n";
1868 OS << "// The main instruction selector code.\n"
1869 << "SDNode *SelectCode(SDNode *N) {\n"
1870 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1871 << " switch (N->getOpcode()) {\n"
1873 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
1875 << " case ISD::EntryToken: // These nodes remain the same.\n"
1876 << " case ISD::BasicBlock:\n"
1877 << " case ISD::Register:\n"
1878 << " case ISD::HANDLENODE:\n"
1879 << " case ISD::TargetConstant:\n"
1880 << " case ISD::TargetConstantFP:\n"
1881 << " case ISD::TargetConstantPool:\n"
1882 << " case ISD::TargetFrameIndex:\n"
1883 << " case ISD::TargetExternalSymbol:\n"
1884 << " case ISD::TargetBlockAddress:\n"
1885 << " case ISD::TargetJumpTable:\n"
1886 << " case ISD::TargetGlobalTLSAddress:\n"
1887 << " case ISD::TargetGlobalAddress:\n"
1888 << " case ISD::TokenFactor:\n"
1889 << " case ISD::CopyFromReg:\n"
1890 << " case ISD::CopyToReg: {\n"
1891 << " return NULL;\n"
1893 << " case ISD::AssertSext:\n"
1894 << " case ISD::AssertZext: {\n"
1895 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
1896 << " return NULL;\n"
1898 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1899 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1900 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1902 // Loop over all of the case statements, emiting a call to each method we
1904 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1905 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1906 PBOI != E; ++PBOI) {
1907 const std::string &OpName = PBOI->first;
1908 // Potentially multiple versions of select for this opcode. One for each
1909 // ValueType of the node (or its first true operand if it doesn't produce a
1911 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1912 OpcodeVTMap.find(OpName);
1913 std::vector<std::string> &OpVTs = OpVTI->second;
1914 OS << " case " << OpName << ": {\n";
1915 // If we have only one variant and it's the default, elide the
1916 // switch. Marginally faster, and makes MSVC happier.
1917 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1918 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1923 // Keep track of whether we see a pattern that has an iPtr result.
1924 bool HasPtrPattern = false;
1925 bool HasDefaultPattern = false;
1927 OS << " switch (NVT) {\n";
1928 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1929 std::string &VTStr = OpVTs[i];
1930 if (VTStr.empty()) {
1931 HasDefaultPattern = true;
1935 // If this is a match on iPTR: don't emit it directly, we need special
1937 if (VTStr == "_iPTR") {
1938 HasPtrPattern = true;
1941 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1942 << " return Select_" << getLegalCName(OpName)
1943 << VTStr << "(N);\n";
1945 OS << " default:\n";
1947 // If there is an iPTR result version of this pattern, emit it here.
1948 if (HasPtrPattern) {
1949 OS << " if (TLI.getPointerTy() == NVT)\n";
1950 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1952 if (HasDefaultPattern) {
1953 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1961 OS << " } // end of big switch.\n\n"
1962 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1963 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1964 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
1965 << " CannotYetSelect(N);\n"
1967 << " CannotYetSelectIntrinsic(N);\n"
1969 << " return NULL;\n"
1973 void DAGISelEmitter::run(raw_ostream &OS) {
1974 EmitSourceFileHeader("DAG Instruction Selector for the " +
1975 CGP.getTargetInfo().getName() + " target", OS);
1977 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1978 << "// *** instruction selector class. These functions are really "
1981 OS << "// Include standard, target-independent definitions and methods used\n"
1982 << "// by the instruction selector.\n";
1983 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
1985 EmitNodeTransforms(OS);
1986 EmitPredicateFunctions(OS);
1988 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
1989 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1991 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1992 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1993 DEBUG(errs() << "\n");
1996 // At this point, we have full information about the 'Patterns' we need to
1997 // parse, both implicitly from instructions as well as from explicit pattern
1998 // definitions. Emit the resultant instruction selector.
1999 EmitInstructionSelector(OS);
2002 MatcherNode *Matcher = 0;
2003 // Walk the patterns backwards, building a matcher for each and adding it to
2004 // the matcher for the whole target.
2005 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
2006 E = CGP.ptm_end(); I != E;) {
2007 const PatternToMatch &Pattern = *--E;
2008 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
2013 Matcher = new PushMatcherNode(N, Matcher);
2017 EmitMatcherTable(Matcher, OS);