1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/Debug.h"
18 #include "llvm/Support/MathExtras.h"
19 #include "llvm/Support/Streams.h"
23 //===----------------------------------------------------------------------===//
24 // DAGISelEmitter implementation
28 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
30 static bool NodeIsComplexPattern(TreePatternNode *N) {
31 return (N->isLeaf() &&
32 dynamic_cast<DefInit*>(N->getLeafValue()) &&
33 static_cast<DefInit*>(N->getLeafValue())->getDef()->
34 isSubClassOf("ComplexPattern"));
37 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
38 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
39 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
40 CodegenDAGPatterns &CGP) {
42 dynamic_cast<DefInit*>(N->getLeafValue()) &&
43 static_cast<DefInit*>(N->getLeafValue())->getDef()->
44 isSubClassOf("ComplexPattern")) {
45 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
51 /// getPatternSize - Return the 'size' of this pattern. We want to match large
52 /// patterns before small ones. This is used to determine the size of a
54 static unsigned getPatternSize(TreePatternNode *P, CodegenDAGPatterns &CGP) {
55 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
56 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
57 P->getExtTypeNum(0) == MVT::isVoid ||
58 P->getExtTypeNum(0) == MVT::Flag ||
59 P->getExtTypeNum(0) == MVT::iPTR) &&
60 "Not a valid pattern node to size!");
61 unsigned Size = 3; // The node itself.
62 // If the root node is a ConstantSDNode, increases its size.
63 // e.g. (set R32:$dst, 0).
64 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
67 // FIXME: This is a hack to statically increase the priority of patterns
68 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
69 // Later we can allow complexity / cost for each pattern to be (optionally)
70 // specified. To get best possible pattern match we'll need to dynamically
71 // calculate the complexity of all patterns a dag can potentially map to.
72 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
74 Size += AM->getNumOperands() * 3;
76 // If this node has some predicate function that must match, it adds to the
77 // complexity of this node.
78 if (!P->getPredicateFn().empty())
81 // Count children in the count if they are also nodes.
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
83 TreePatternNode *Child = P->getChild(i);
84 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
85 Size += getPatternSize(Child, CGP);
86 else if (Child->isLeaf()) {
87 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
88 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
89 else if (NodeIsComplexPattern(Child))
90 Size += getPatternSize(Child, CGP);
91 else if (!Child->getPredicateFn().empty())
99 /// getResultPatternCost - Compute the number of instructions for this pattern.
100 /// This is a temporary hack. We should really include the instruction
101 /// latencies in this calculation.
102 static unsigned getResultPatternCost(TreePatternNode *P,
103 CodegenDAGPatterns &CGP) {
104 if (P->isLeaf()) return 0;
107 Record *Op = P->getOperator();
108 if (Op->isSubClassOf("Instruction")) {
110 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
111 if (II.usesCustomDAGSchedInserter)
114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
115 Cost += getResultPatternCost(P->getChild(i), CGP);
119 /// getResultPatternCodeSize - Compute the code size of instructions for this
121 static unsigned getResultPatternSize(TreePatternNode *P,
122 CodegenDAGPatterns &CGP) {
123 if (P->isLeaf()) return 0;
126 Record *Op = P->getOperator();
127 if (Op->isSubClassOf("Instruction")) {
128 Cost += Op->getValueAsInt("CodeSize");
130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
131 Cost += getResultPatternSize(P->getChild(i), CGP);
135 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
136 // In particular, we want to match maximal patterns first and lowest cost within
137 // a particular complexity first.
138 struct PatternSortingPredicate {
139 PatternSortingPredicate(CodegenDAGPatterns &cgp) : CGP(cgp) {}
140 CodegenDAGPatterns &CGP;
142 bool operator()(const PatternToMatch *LHS,
143 const PatternToMatch *RHS) {
144 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
145 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
146 LHSSize += LHS->getAddedComplexity();
147 RHSSize += RHS->getAddedComplexity();
148 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
149 if (LHSSize < RHSSize) return false;
151 // If the patterns have equal complexity, compare generated instruction cost
152 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
153 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
154 if (LHSCost < RHSCost) return true;
155 if (LHSCost > RHSCost) return false;
157 return getResultPatternSize(LHS->getDstPattern(), CGP) <
158 getResultPatternSize(RHS->getDstPattern(), CGP);
162 /// getRegisterValueType - Look up and return the first ValueType of specified
163 /// RegisterClass record
164 static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
165 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
166 return RC->getValueTypeNum(0);
171 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
172 /// type information from it.
173 static void RemoveAllTypes(TreePatternNode *N) {
176 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
177 RemoveAllTypes(N->getChild(i));
180 /// NodeHasProperty - return true if TreePatternNode has the specified
182 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
183 CodegenDAGPatterns &CGP) {
185 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
187 return CP->hasProperty(Property);
190 Record *Operator = N->getOperator();
191 if (!Operator->isSubClassOf("SDNode")) return false;
193 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
196 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
197 CodegenDAGPatterns &CGP) {
198 if (NodeHasProperty(N, Property, CGP))
201 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
202 TreePatternNode *Child = N->getChild(i);
203 if (PatternHasProperty(Child, Property, CGP))
210 class PatternCodeEmitter {
212 CodegenDAGPatterns &CGP;
215 ListInit *Predicates;
218 // Instruction selector pattern.
219 TreePatternNode *Pattern;
220 // Matched instruction.
221 TreePatternNode *Instruction;
223 // Node to name mapping
224 std::map<std::string, std::string> VariableMap;
225 // Node to operator mapping
226 std::map<std::string, Record*> OperatorMap;
227 // Names of all the folded nodes which produce chains.
228 std::vector<std::pair<std::string, unsigned> > FoldedChains;
229 // Original input chain(s).
230 std::vector<std::pair<std::string, std::string> > OrigChains;
231 std::set<std::string> Duplicates;
233 /// GeneratedCode - This is the buffer that we emit code to. The first int
234 /// indicates whether this is an exit predicate (something that should be
235 /// tested, and if true, the match fails) [when 1], or normal code to emit
236 /// [when 0], or initialization code to emit [when 2].
237 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
238 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
239 /// the set of patterns for each top-level opcode.
240 std::set<std::string> &GeneratedDecl;
241 /// TargetOpcodes - The target specific opcodes used by the resulting
243 std::vector<std::string> &TargetOpcodes;
244 std::vector<std::string> &TargetVTs;
246 std::string ChainName;
251 void emitCheck(const std::string &S) {
253 GeneratedCode.push_back(std::make_pair(1, S));
255 void emitCode(const std::string &S) {
257 GeneratedCode.push_back(std::make_pair(0, S));
259 void emitInit(const std::string &S) {
261 GeneratedCode.push_back(std::make_pair(2, S));
263 void emitDecl(const std::string &S) {
264 assert(!S.empty() && "Invalid declaration");
265 GeneratedDecl.insert(S);
267 void emitOpcode(const std::string &Opc) {
268 TargetOpcodes.push_back(Opc);
271 void emitVT(const std::string &VT) {
272 TargetVTs.push_back(VT);
276 PatternCodeEmitter(CodegenDAGPatterns &cgp, ListInit *preds,
277 TreePatternNode *pattern, TreePatternNode *instr,
278 std::vector<std::pair<unsigned, std::string> > &gc,
279 std::set<std::string> &gd,
280 std::vector<std::string> &to,
281 std::vector<std::string> &tv)
282 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
283 GeneratedCode(gc), GeneratedDecl(gd),
284 TargetOpcodes(to), TargetVTs(tv),
285 TmpNo(0), OpcNo(0), VTNo(0) {}
287 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
288 /// if the match fails. At this point, we already know that the opcode for N
289 /// matches, and the SDNode for the result has the RootName specified name.
290 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
291 const std::string &RootName, const std::string &ChainSuffix,
293 bool isRoot = (P == NULL);
294 // Emit instruction predicates. Each predicate is just a string for now.
296 std::string PredicateCheck;
297 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
298 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
299 Record *Def = Pred->getDef();
300 if (!Def->isSubClassOf("Predicate")) {
304 assert(0 && "Unknown predicate type!");
306 if (!PredicateCheck.empty())
307 PredicateCheck += " && ";
308 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
312 emitCheck(PredicateCheck);
316 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
317 emitCheck("cast<ConstantSDNode>(" + RootName +
318 ")->getSignExtended() == " + itostr(II->getValue()));
320 } else if (!NodeIsComplexPattern(N)) {
321 assert(0 && "Cannot match this as a leaf value!");
326 // If this node has a name associated with it, capture it in VariableMap. If
327 // we already saw this in the pattern, emit code to verify dagness.
328 if (!N->getName().empty()) {
329 std::string &VarMapEntry = VariableMap[N->getName()];
330 if (VarMapEntry.empty()) {
331 VarMapEntry = RootName;
333 // If we get here, this is a second reference to a specific name. Since
334 // we already have checked that the first reference is valid, we don't
335 // have to recursively match it, just check that it's the same as the
336 // previously named thing.
337 emitCheck(VarMapEntry + " == " + RootName);
342 OperatorMap[N->getName()] = N->getOperator();
346 // Emit code to load the child nodes and match their contents recursively.
348 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
349 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
350 bool EmittedUseCheck = false;
355 // Multiple uses of actual result?
356 emitCheck(RootName + ".hasOneUse()");
357 EmittedUseCheck = true;
359 // If the immediate use can somehow reach this node through another
360 // path, then can't fold it either or it will create a cycle.
361 // e.g. In the following diagram, XX can reach ld through YY. If
362 // ld is folded into XX, then YY is both a predecessor and a successor
372 bool NeedCheck = false;
376 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
378 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
379 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
380 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
381 PInfo.getNumOperands() > 1 ||
382 PInfo.hasProperty(SDNPHasChain) ||
383 PInfo.hasProperty(SDNPInFlag) ||
384 PInfo.hasProperty(SDNPOptInFlag);
388 std::string ParentName(RootName.begin(), RootName.end()-1);
389 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
397 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
398 "IsChainCompatible(" + ChainName + ".Val, " +
399 RootName + ".Val))");
400 OrigChains.push_back(std::make_pair(ChainName, RootName));
403 ChainName = "Chain" + ChainSuffix;
404 emitInit("SDOperand " + ChainName + " = " + RootName +
409 // Don't fold any node which reads or writes a flag and has multiple uses.
410 // FIXME: We really need to separate the concepts of flag and "glue". Those
411 // real flag results, e.g. X86CMP output, can have multiple uses.
412 // FIXME: If the optional incoming flag does not exist. Then it is ok to
415 (PatternHasProperty(N, SDNPInFlag, CGP) ||
416 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
417 PatternHasProperty(N, SDNPOutFlag, CGP))) {
418 if (!EmittedUseCheck) {
419 // Multiple uses of actual result?
420 emitCheck(RootName + ".hasOneUse()");
424 // If there is a node predicate for this, emit the call.
425 if (!N->getPredicateFn().empty())
426 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
429 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
430 // a constant without a predicate fn that has more that one bit set, handle
431 // this as a special case. This is usually for targets that have special
432 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
433 // handling stuff). Using these instructions is often far more efficient
434 // than materializing the constant. Unfortunately, both the instcombiner
435 // and the dag combiner can often infer that bits are dead, and thus drop
436 // them from the mask in the dag. For example, it might turn 'AND X, 255'
437 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
440 (N->getOperator()->getName() == "and" ||
441 N->getOperator()->getName() == "or") &&
442 N->getChild(1)->isLeaf() &&
443 N->getChild(1)->getPredicateFn().empty()) {
444 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
445 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
446 emitInit("SDOperand " + RootName + "0" + " = " +
447 RootName + ".getOperand(" + utostr(0) + ");");
448 emitInit("SDOperand " + RootName + "1" + " = " +
449 RootName + ".getOperand(" + utostr(1) + ");");
451 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
452 const char *MaskPredicate = N->getOperator()->getName() == "or"
453 ? "CheckOrMask(" : "CheckAndMask(";
454 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
455 RootName + "1), " + itostr(II->getValue()) + ")");
457 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
458 ChainSuffix + utostr(0), FoundChain);
464 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
465 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
466 RootName + ".getOperand(" +utostr(OpNo) + ");");
468 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
469 ChainSuffix + utostr(OpNo), FoundChain);
472 // Handle cases when root is a complex pattern.
473 const ComplexPattern *CP;
474 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
475 std::string Fn = CP->getSelectFunc();
476 unsigned NumOps = CP->getNumOperands();
477 for (unsigned i = 0; i < NumOps; ++i) {
478 emitDecl("CPTmp" + utostr(i));
479 emitCode("SDOperand CPTmp" + utostr(i) + ";");
481 if (CP->hasProperty(SDNPHasChain)) {
482 emitDecl("CPInChain");
483 emitDecl("Chain" + ChainSuffix);
484 emitCode("SDOperand CPInChain;");
485 emitCode("SDOperand Chain" + ChainSuffix + ";");
488 std::string Code = Fn + "(" + RootName + ", " + RootName;
489 for (unsigned i = 0; i < NumOps; i++)
490 Code += ", CPTmp" + utostr(i);
491 if (CP->hasProperty(SDNPHasChain)) {
492 ChainName = "Chain" + ChainSuffix;
493 Code += ", CPInChain, Chain" + ChainSuffix;
495 emitCheck(Code + ")");
499 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
500 const std::string &RootName,
501 const std::string &ChainSuffix, bool &FoundChain) {
502 if (!Child->isLeaf()) {
503 // If it's not a leaf, recursively match.
504 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
505 emitCheck(RootName + ".getOpcode() == " +
506 CInfo.getEnumName());
507 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
508 if (NodeHasProperty(Child, SDNPHasChain, CGP))
509 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
511 // If this child has a name associated with it, capture it in VarMap. If
512 // we already saw this in the pattern, emit code to verify dagness.
513 if (!Child->getName().empty()) {
514 std::string &VarMapEntry = VariableMap[Child->getName()];
515 if (VarMapEntry.empty()) {
516 VarMapEntry = RootName;
518 // If we get here, this is a second reference to a specific name.
519 // Since we already have checked that the first reference is valid,
520 // we don't have to recursively match it, just check that it's the
521 // same as the previously named thing.
522 emitCheck(VarMapEntry + " == " + RootName);
523 Duplicates.insert(RootName);
528 // Handle leaves of various types.
529 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
530 Record *LeafRec = DI->getDef();
531 if (LeafRec->isSubClassOf("RegisterClass") ||
532 LeafRec->getName() == "ptr_rc") {
533 // Handle register references. Nothing to do here.
534 } else if (LeafRec->isSubClassOf("Register")) {
535 // Handle register references.
536 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
537 // Handle complex pattern.
538 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
539 std::string Fn = CP->getSelectFunc();
540 unsigned NumOps = CP->getNumOperands();
541 for (unsigned i = 0; i < NumOps; ++i) {
542 emitDecl("CPTmp" + utostr(i));
543 emitCode("SDOperand CPTmp" + utostr(i) + ";");
545 if (CP->hasProperty(SDNPHasChain)) {
546 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
547 FoldedChains.push_back(std::make_pair("CPInChain",
548 PInfo.getNumResults()));
549 ChainName = "Chain" + ChainSuffix;
550 emitDecl("CPInChain");
552 emitCode("SDOperand CPInChain;");
553 emitCode("SDOperand " + ChainName + ";");
556 std::string Code = Fn + "(N, ";
557 if (CP->hasProperty(SDNPHasChain)) {
558 std::string ParentName(RootName.begin(), RootName.end()-1);
559 Code += ParentName + ", ";
562 for (unsigned i = 0; i < NumOps; i++)
563 Code += ", CPTmp" + utostr(i);
564 if (CP->hasProperty(SDNPHasChain))
565 Code += ", CPInChain, Chain" + ChainSuffix;
566 emitCheck(Code + ")");
567 } else if (LeafRec->getName() == "srcvalue") {
568 // Place holder for SRCVALUE nodes. Nothing to do here.
569 } else if (LeafRec->isSubClassOf("ValueType")) {
570 // Make sure this is the specified value type.
571 emitCheck("cast<VTSDNode>(" + RootName +
572 ")->getVT() == MVT::" + LeafRec->getName());
573 } else if (LeafRec->isSubClassOf("CondCode")) {
574 // Make sure this is the specified cond code.
575 emitCheck("cast<CondCodeSDNode>(" + RootName +
576 ")->get() == ISD::" + LeafRec->getName());
582 assert(0 && "Unknown leaf type!");
585 // If there is a node predicate for this, emit the call.
586 if (!Child->getPredicateFn().empty())
587 emitCheck(Child->getPredicateFn() + "(" + RootName +
589 } else if (IntInit *II =
590 dynamic_cast<IntInit*>(Child->getLeafValue())) {
591 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
592 unsigned CTmp = TmpNo++;
593 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
594 RootName + ")->getSignExtended();");
596 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
601 assert(0 && "Unknown leaf type!");
606 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
607 /// we actually have to build a DAG!
608 std::vector<std::string>
609 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
610 bool InFlagDecled, bool ResNodeDecled,
611 bool LikeLeaf = false, bool isRoot = false) {
612 // List of arguments of getTargetNode() or SelectNodeTo().
613 std::vector<std::string> NodeOps;
614 // This is something selected from the pattern we matched.
615 if (!N->getName().empty()) {
616 std::string &Val = VariableMap[N->getName()];
617 assert(!Val.empty() &&
618 "Variable referenced but not defined and not caught earlier!");
619 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
620 // Already selected this operand, just return the tmpval.
621 NodeOps.push_back(Val);
625 const ComplexPattern *CP;
626 unsigned ResNo = TmpNo++;
627 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
628 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
629 std::string CastType;
630 switch (N->getTypeNum(0)) {
632 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
633 << " type as an immediate constant. Aborting\n";
635 case MVT::i1: CastType = "bool"; break;
636 case MVT::i8: CastType = "unsigned char"; break;
637 case MVT::i16: CastType = "unsigned short"; break;
638 case MVT::i32: CastType = "unsigned"; break;
639 case MVT::i64: CastType = "uint64_t"; break;
641 emitCode("SDOperand Tmp" + utostr(ResNo) +
642 " = CurDAG->getTargetConstant(((" + CastType +
643 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
644 getEnumName(N->getTypeNum(0)) + ");");
645 NodeOps.push_back("Tmp" + utostr(ResNo));
646 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
647 // value if used multiple times by this pattern result.
648 Val = "Tmp"+utostr(ResNo);
649 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
650 Record *Op = OperatorMap[N->getName()];
651 // Transform ExternalSymbol to TargetExternalSymbol
652 if (Op && Op->getName() == "externalsym") {
653 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
654 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
655 Val + ")->getSymbol(), " +
656 getEnumName(N->getTypeNum(0)) + ");");
657 NodeOps.push_back("Tmp" + utostr(ResNo));
658 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
659 // this value if used multiple times by this pattern result.
660 Val = "Tmp"+utostr(ResNo);
662 NodeOps.push_back(Val);
664 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
665 || N->getOperator()->getName() == "tglobaltlsaddr")) {
666 Record *Op = OperatorMap[N->getName()];
667 // Transform GlobalAddress to TargetGlobalAddress
668 if (Op && (Op->getName() == "globaladdr" ||
669 Op->getName() == "globaltlsaddr")) {
670 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getTarget"
671 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
672 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
674 NodeOps.push_back("Tmp" + utostr(ResNo));
675 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
676 // this value if used multiple times by this pattern result.
677 Val = "Tmp"+utostr(ResNo);
679 NodeOps.push_back(Val);
681 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
682 NodeOps.push_back(Val);
683 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
684 // value if used multiple times by this pattern result.
685 Val = "Tmp"+utostr(ResNo);
686 } else if (!N->isLeaf() && N->getOperator()->getName() == "tconstpool") {
687 NodeOps.push_back(Val);
688 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
689 // value if used multiple times by this pattern result.
690 Val = "Tmp"+utostr(ResNo);
691 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
692 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
693 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
694 NodeOps.push_back("CPTmp" + utostr(i));
697 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
698 // node even if it isn't one. Don't select it.
700 emitCode("AddToISelQueue(" + Val + ");");
701 if (isRoot && N->isLeaf()) {
702 emitCode("ReplaceUses(N, " + Val + ");");
703 emitCode("return NULL;");
706 NodeOps.push_back(Val);
711 // If this is an explicit register reference, handle it.
712 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
713 unsigned ResNo = TmpNo++;
714 if (DI->getDef()->isSubClassOf("Register")) {
715 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
716 getQualifiedName(DI->getDef()) + ", " +
717 getEnumName(N->getTypeNum(0)) + ");");
718 NodeOps.push_back("Tmp" + utostr(ResNo));
720 } else if (DI->getDef()->getName() == "zero_reg") {
721 emitCode("SDOperand Tmp" + utostr(ResNo) +
722 " = CurDAG->getRegister(0, " +
723 getEnumName(N->getTypeNum(0)) + ");");
724 NodeOps.push_back("Tmp" + utostr(ResNo));
727 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
728 unsigned ResNo = TmpNo++;
729 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
730 emitCode("SDOperand Tmp" + utostr(ResNo) +
731 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
732 ", " + getEnumName(N->getTypeNum(0)) + ");");
733 NodeOps.push_back("Tmp" + utostr(ResNo));
740 assert(0 && "Unknown leaf type!");
744 Record *Op = N->getOperator();
745 if (Op->isSubClassOf("Instruction")) {
746 const CodeGenTarget &CGT = CGP.getTargetInfo();
747 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
748 const DAGInstruction &Inst = CGP.getInstruction(Op);
749 TreePattern *InstPat = Inst.getPattern();
750 // FIXME: Assume actual pattern comes before "implicit".
751 TreePatternNode *InstPatNode =
752 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
753 : (InstPat ? InstPat->getTree(0) : NULL);
754 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
755 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
757 bool HasVarOps = isRoot && II.hasVariableNumberOfOperands;
758 // FIXME: fix how we deal with physical register operands.
759 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
760 bool HasImpResults = isRoot && DstRegs.size() > 0;
761 bool NodeHasOptInFlag = isRoot &&
762 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
763 bool NodeHasInFlag = isRoot &&
764 PatternHasProperty(Pattern, SDNPInFlag, CGP);
765 bool NodeHasOutFlag = isRoot &&
766 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
767 bool NodeHasChain = InstPatNode &&
768 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
769 bool InputHasChain = isRoot &&
770 NodeHasProperty(Pattern, SDNPHasChain, CGP);
771 unsigned NumResults = Inst.getNumResults();
772 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
774 if (NodeHasOptInFlag) {
775 emitCode("bool HasInFlag = "
776 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
779 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
781 // How many results is this pattern expected to produce?
782 unsigned NumPatResults = 0;
783 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
784 MVT::ValueType VT = Pattern->getTypeNum(i);
785 if (VT != MVT::isVoid && VT != MVT::Flag)
789 if (OrigChains.size() > 0) {
790 // The original input chain is being ignored. If it is not just
791 // pointing to the op that's being folded, we should create a
792 // TokenFactor with it and the chain of the folded op as the new chain.
793 // We could potentially be doing multiple levels of folding, in that
794 // case, the TokenFactor can have more operands.
795 emitCode("SmallVector<SDOperand, 8> InChains;");
796 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
797 emitCode("if (" + OrigChains[i].first + ".Val != " +
798 OrigChains[i].second + ".Val) {");
799 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
800 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
803 emitCode("AddToISelQueue(" + ChainName + ");");
804 emitCode("InChains.push_back(" + ChainName + ");");
805 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
806 "&InChains[0], InChains.size());");
809 // Loop over all of the operands of the instruction pattern, emitting code
810 // to fill them all in. The node 'N' usually has number children equal to
811 // the number of input operands of the instruction. However, in cases
812 // where there are predicate operands for an instruction, we need to fill
813 // in the 'execute always' values. Match up the node operands to the
814 // instruction operands to do this.
815 std::vector<std::string> AllOps;
816 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
817 for (unsigned ChildNo = 0, InstOpNo = NumResults;
818 InstOpNo != II.OperandList.size(); ++InstOpNo) {
819 std::vector<std::string> Ops;
821 // If this is a normal operand or a predicate operand without
822 // 'execute always', emit it.
823 Record *OperandNode = II.OperandList[InstOpNo].Rec;
824 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
825 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
826 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
827 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
828 InFlagDecled, ResNodeDecled);
829 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
832 // Otherwise, this is a predicate or optional def operand, emit the
833 // 'default ops' operands.
834 const DAGDefaultOperand &DefaultOp =
835 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
836 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
837 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
838 InFlagDecled, ResNodeDecled);
839 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
840 NumEAInputs += Ops.size();
845 // Emit all the chain and CopyToReg stuff.
846 bool ChainEmitted = NodeHasChain;
848 emitCode("AddToISelQueue(" + ChainName + ");");
849 if (NodeHasInFlag || HasImpInputs)
850 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
851 InFlagDecled, ResNodeDecled, true);
852 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
854 emitCode("SDOperand InFlag(0, 0);");
857 if (NodeHasOptInFlag) {
858 emitCode("if (HasInFlag) {");
859 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
860 emitCode(" AddToISelQueue(InFlag);");
865 unsigned ResNo = TmpNo++;
866 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
867 NodeHasOptInFlag || HasImpResults) {
870 std::string NodeName;
872 NodeName = "Tmp" + utostr(ResNo);
873 Code2 = "SDOperand " + NodeName + "(";
875 NodeName = "ResNode";
876 if (!ResNodeDecled) {
877 Code2 = "SDNode *" + NodeName + " = ";
878 ResNodeDecled = true;
880 Code2 = NodeName + " = ";
883 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
884 unsigned OpsNo = OpcNo;
885 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
887 // Output order: results, chain, flags
889 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
890 Code += ", VT" + utostr(VTNo);
891 emitVT(getEnumName(N->getTypeNum(0)));
893 // Add types for implicit results in physical registers, scheduler will
894 // care of adding copyfromreg nodes.
895 for (unsigned i = 0; i < NumDstRegs; i++) {
896 Record *RR = DstRegs[i];
897 if (RR->isSubClassOf("Register")) {
898 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
899 Code += ", " + getEnumName(RVT);
903 Code += ", MVT::Other";
905 Code += ", MVT::Flag";
907 // Figure out how many fixed inputs the node has. This is important to
908 // know which inputs are the variable ones if present.
909 unsigned NumInputs = AllOps.size();
910 NumInputs += NodeHasChain;
914 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
915 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
920 // Figure out whether any operands at the end of the op list are not
921 // part of the variable section.
922 std::string EndAdjust;
923 if (NodeHasInFlag || HasImpInputs)
924 EndAdjust = "-1"; // Always has one flag.
925 else if (NodeHasOptInFlag)
926 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
928 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
929 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
931 emitCode(" AddToISelQueue(N.getOperand(i));");
932 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
938 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
940 AllOps.push_back(ChainName);
944 if (NodeHasInFlag || HasImpInputs)
945 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
946 else if (NodeHasOptInFlag) {
947 emitCode("if (HasInFlag)");
948 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
950 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
952 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
953 AllOps.push_back("InFlag");
955 unsigned NumOps = AllOps.size();
957 if (!NodeHasOptInFlag && NumOps < 4) {
958 for (unsigned i = 0; i != NumOps; ++i)
959 Code += ", " + AllOps[i];
961 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
962 for (unsigned i = 0; i != NumOps; ++i) {
963 OpsCode += AllOps[i];
967 emitCode(OpsCode + " };");
968 Code += ", Ops" + utostr(OpsNo) + ", ";
969 if (NodeHasOptInFlag) {
970 Code += "HasInFlag ? ";
971 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
973 Code += utostr(NumOps);
979 emitCode(Code2 + Code + ");");
982 // Remember which op produces the chain.
984 emitCode(ChainName + " = SDOperand(" + NodeName +
985 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
987 emitCode(ChainName + " = SDOperand(" + NodeName +
988 ", " + utostr(NumResults+NumDstRegs) + ");");
991 NodeOps.push_back("Tmp" + utostr(ResNo));
995 bool NeedReplace = false;
996 if (NodeHasOutFlag) {
998 emitCode("SDOperand InFlag(ResNode, " +
999 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1000 InFlagDecled = true;
1002 emitCode("InFlag = SDOperand(ResNode, " +
1003 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
1006 if (FoldedChains.size() > 0) {
1008 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1009 emitCode("ReplaceUses(SDOperand(" +
1010 FoldedChains[j].first + ".Val, " +
1011 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
1012 utostr(NumResults+NumDstRegs) + "));");
1016 if (NodeHasOutFlag) {
1017 emitCode("ReplaceUses(SDOperand(N.Val, " +
1018 utostr(NumPatResults + (unsigned)InputHasChain)
1023 if (NeedReplace && InputHasChain)
1024 emitCode("ReplaceUses(SDOperand(N.Val, " +
1025 utostr(NumPatResults) + "), SDOperand(" + ChainName
1026 + ".Val, " + ChainName + ".ResNo" + "));");
1028 // User does not expect the instruction would produce a chain!
1029 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1031 } else if (InputHasChain && !NodeHasChain) {
1032 // One of the inner node produces a chain.
1034 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
1035 "), SDOperand(ResNode, N.ResNo-1));");
1036 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
1037 "), " + ChainName + ");");
1040 emitCode("return ResNode;");
1042 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1044 if (N->getTypeNum(0) != MVT::isVoid)
1045 Code += ", VT" + utostr(VTNo);
1047 Code += ", MVT::Flag";
1049 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1050 AllOps.push_back("InFlag");
1052 unsigned NumOps = AllOps.size();
1054 if (!NodeHasOptInFlag && NumOps < 4) {
1055 for (unsigned i = 0; i != NumOps; ++i)
1056 Code += ", " + AllOps[i];
1058 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1059 for (unsigned i = 0; i != NumOps; ++i) {
1060 OpsCode += AllOps[i];
1064 emitCode(OpsCode + " };");
1065 Code += ", Ops" + utostr(OpcNo) + ", ";
1066 Code += utostr(NumOps);
1069 emitCode(Code + ");");
1070 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1071 if (N->getTypeNum(0) != MVT::isVoid)
1072 emitVT(getEnumName(N->getTypeNum(0)));
1076 } else if (Op->isSubClassOf("SDNodeXForm")) {
1077 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1078 // PatLeaf node - the operand may or may not be a leaf node. But it should
1080 std::vector<std::string> Ops =
1081 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1082 ResNodeDecled, true);
1083 unsigned ResNo = TmpNo++;
1084 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1085 + "(" + Ops.back() + ".Val);");
1086 NodeOps.push_back("Tmp" + utostr(ResNo));
1088 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1093 throw std::string("Unknown node in result pattern!");
1097 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1098 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1099 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1100 /// for, this returns true otherwise false if Pat has all types.
1101 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1102 const std::string &Prefix, bool isRoot = false) {
1104 if (Pat->getExtTypes() != Other->getExtTypes()) {
1105 // Move a type over from 'other' to 'pat'.
1106 Pat->setTypes(Other->getExtTypes());
1107 // The top level node type is checked outside of the select function.
1109 emitCheck(Prefix + ".Val->getValueType(0) == " +
1110 getName(Pat->getTypeNum(0)));
1115 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1116 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1117 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1118 Prefix + utostr(OpNo)))
1124 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1126 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1127 bool &ChainEmitted, bool &InFlagDecled,
1128 bool &ResNodeDecled, bool isRoot = false) {
1129 const CodeGenTarget &T = CGP.getTargetInfo();
1131 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1132 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1133 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1134 TreePatternNode *Child = N->getChild(i);
1135 if (!Child->isLeaf()) {
1136 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1137 InFlagDecled, ResNodeDecled);
1139 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1140 if (!Child->getName().empty()) {
1141 std::string Name = RootName + utostr(OpNo);
1142 if (Duplicates.find(Name) != Duplicates.end())
1143 // A duplicate! Do not emit a copy for this node.
1147 Record *RR = DI->getDef();
1148 if (RR->isSubClassOf("Register")) {
1149 MVT::ValueType RVT = getRegisterValueType(RR, T);
1150 if (RVT == MVT::Flag) {
1151 if (!InFlagDecled) {
1152 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1153 InFlagDecled = true;
1155 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1156 emitCode("AddToISelQueue(InFlag);");
1158 if (!ChainEmitted) {
1159 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1160 ChainName = "Chain";
1161 ChainEmitted = true;
1163 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1164 if (!InFlagDecled) {
1165 emitCode("SDOperand InFlag(0, 0);");
1166 InFlagDecled = true;
1168 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1169 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1170 ", " + getQualifiedName(RR) +
1171 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1172 ResNodeDecled = true;
1173 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1174 emitCode("InFlag = SDOperand(ResNode, 1);");
1182 if (!InFlagDecled) {
1183 emitCode("SDOperand InFlag = " + RootName +
1184 ".getOperand(" + utostr(OpNo) + ");");
1185 InFlagDecled = true;
1187 emitCode("InFlag = " + RootName +
1188 ".getOperand(" + utostr(OpNo) + ");");
1189 emitCode("AddToISelQueue(InFlag);");
1194 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1195 /// stream to match the pattern, and generate the code for the match if it
1196 /// succeeds. Returns true if the pattern is not guaranteed to match.
1197 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1198 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1199 std::set<std::string> &GeneratedDecl,
1200 std::vector<std::string> &TargetOpcodes,
1201 std::vector<std::string> &TargetVTs) {
1202 PatternCodeEmitter Emitter(*CGP, Pattern.getPredicates(),
1203 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1204 GeneratedCode, GeneratedDecl,
1205 TargetOpcodes, TargetVTs);
1207 // Emit the matcher, capturing named arguments in VariableMap.
1208 bool FoundChain = false;
1209 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1211 // TP - Get *SOME* tree pattern, we don't care which.
1212 TreePattern &TP = *CGP->pf_begin()->second;
1214 // At this point, we know that we structurally match the pattern, but the
1215 // types of the nodes may not match. Figure out the fewest number of type
1216 // comparisons we need to emit. For example, if there is only one integer
1217 // type supported by a target, there should be no type comparisons at all for
1218 // integer patterns!
1220 // To figure out the fewest number of type checks needed, clone the pattern,
1221 // remove the types, then perform type inference on the pattern as a whole.
1222 // If there are unresolved types, emit an explicit check for those types,
1223 // apply the type to the tree, then rerun type inference. Iterate until all
1224 // types are resolved.
1226 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1227 RemoveAllTypes(Pat);
1230 // Resolve/propagate as many types as possible.
1232 bool MadeChange = true;
1234 MadeChange = Pat->ApplyTypeConstraints(TP,
1235 true/*Ignore reg constraints*/);
1237 assert(0 && "Error: could not find consistent types for something we"
1238 " already decided was ok!");
1242 // Insert a check for an unresolved type and add it to the tree. If we find
1243 // an unresolved type to add a check for, this returns true and we iterate,
1244 // otherwise we are done.
1245 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1247 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1248 false, false, false, true);
1252 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1253 /// a line causes any of them to be empty, remove them and return true when
1255 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1256 std::vector<std::pair<unsigned, std::string> > > >
1258 bool ErasedPatterns = false;
1259 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1260 Patterns[i].second.pop_back();
1261 if (Patterns[i].second.empty()) {
1262 Patterns.erase(Patterns.begin()+i);
1264 ErasedPatterns = true;
1267 return ErasedPatterns;
1270 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1271 /// code together between the patterns.
1272 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1273 std::vector<std::pair<unsigned, std::string> > > >
1274 &Patterns, unsigned Indent,
1276 typedef std::pair<unsigned, std::string> CodeLine;
1277 typedef std::vector<CodeLine> CodeList;
1278 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1280 if (Patterns.empty()) return;
1282 // Figure out how many patterns share the next code line. Explicitly copy
1283 // FirstCodeLine so that we don't invalidate a reference when changing
1285 const CodeLine FirstCodeLine = Patterns.back().second.back();
1286 unsigned LastMatch = Patterns.size()-1;
1287 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1290 // If not all patterns share this line, split the list into two pieces. The
1291 // first chunk will use this line, the second chunk won't.
1292 if (LastMatch != 0) {
1293 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1294 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1296 // FIXME: Emit braces?
1297 if (Shared.size() == 1) {
1298 const PatternToMatch &Pattern = *Shared.back().first;
1299 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1300 Pattern.getSrcPattern()->print(OS);
1301 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1302 Pattern.getDstPattern()->print(OS);
1304 unsigned AddedComplexity = Pattern.getAddedComplexity();
1305 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1306 << getPatternSize(Pattern.getSrcPattern(), *CGP) + AddedComplexity
1308 << getResultPatternCost(Pattern.getDstPattern(), *CGP)
1310 << getResultPatternSize(Pattern.getDstPattern(), *CGP) << "\n";
1312 if (FirstCodeLine.first != 1) {
1313 OS << std::string(Indent, ' ') << "{\n";
1316 EmitPatterns(Shared, Indent, OS);
1317 if (FirstCodeLine.first != 1) {
1319 OS << std::string(Indent, ' ') << "}\n";
1322 if (Other.size() == 1) {
1323 const PatternToMatch &Pattern = *Other.back().first;
1324 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1325 Pattern.getSrcPattern()->print(OS);
1326 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1327 Pattern.getDstPattern()->print(OS);
1329 unsigned AddedComplexity = Pattern.getAddedComplexity();
1330 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1331 << getPatternSize(Pattern.getSrcPattern(), *CGP) + AddedComplexity
1333 << getResultPatternCost(Pattern.getDstPattern(), *CGP)
1335 << getResultPatternSize(Pattern.getDstPattern(), *CGP) << "\n";
1337 EmitPatterns(Other, Indent, OS);
1341 // Remove this code from all of the patterns that share it.
1342 bool ErasedPatterns = EraseCodeLine(Patterns);
1344 bool isPredicate = FirstCodeLine.first == 1;
1346 // Otherwise, every pattern in the list has this line. Emit it.
1349 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1351 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1353 // If the next code line is another predicate, and if all of the pattern
1354 // in this group share the same next line, emit it inline now. Do this
1355 // until we run out of common predicates.
1356 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1357 // Check that all of fhe patterns in Patterns end with the same predicate.
1358 bool AllEndWithSamePredicate = true;
1359 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1360 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1361 AllEndWithSamePredicate = false;
1364 // If all of the predicates aren't the same, we can't share them.
1365 if (!AllEndWithSamePredicate) break;
1367 // Otherwise we can. Emit it shared now.
1368 OS << " &&\n" << std::string(Indent+4, ' ')
1369 << Patterns.back().second.back().second;
1370 ErasedPatterns = EraseCodeLine(Patterns);
1377 EmitPatterns(Patterns, Indent, OS);
1380 OS << std::string(Indent-2, ' ') << "}\n";
1383 static std::string getOpcodeName(Record *Op, CodegenDAGPatterns &CGP) {
1384 return CGP.getSDNodeInfo(Op).getEnumName();
1387 static std::string getLegalCName(std::string OpName) {
1388 std::string::size_type pos = OpName.find("::");
1389 if (pos != std::string::npos)
1390 OpName.replace(pos, 2, "_");
1394 void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
1395 const CodeGenTarget &Target = CGP->getTargetInfo();
1397 // Get the namespace to insert instructions into. Make sure not to pick up
1398 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1399 // instruction or something.
1401 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1402 e = Target.inst_end(); i != e; ++i) {
1403 InstNS = i->second.Namespace;
1404 if (InstNS != "TargetInstrInfo")
1408 if (!InstNS.empty()) InstNS += "::";
1410 // Group the patterns by their top-level opcodes.
1411 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1412 // All unique target node emission functions.
1413 std::map<std::string, unsigned> EmitFunctions;
1414 for (CodegenDAGPatterns::ptm_iterator I = CGP->ptm_begin(),
1415 E = CGP->ptm_end(); I != E; ++I) {
1416 const PatternToMatch &Pattern = *I;
1418 TreePatternNode *Node = Pattern.getSrcPattern();
1419 if (!Node->isLeaf()) {
1420 PatternsByOpcode[getOpcodeName(Node->getOperator(), *CGP)].
1421 push_back(&Pattern);
1423 const ComplexPattern *CP;
1424 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1425 PatternsByOpcode[getOpcodeName(CGP->getSDNodeNamed("imm"), *CGP)].
1426 push_back(&Pattern);
1427 } else if ((CP = NodeGetComplexPattern(Node, *CGP))) {
1428 std::vector<Record*> OpNodes = CP->getRootNodes();
1429 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1430 PatternsByOpcode[getOpcodeName(OpNodes[j], *CGP)]
1431 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], *CGP)].begin(),
1435 cerr << "Unrecognized opcode '";
1437 cerr << "' on tree pattern '";
1438 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1444 // For each opcode, there might be multiple select functions, one per
1445 // ValueType of the node (or its first operand if it doesn't produce a
1446 // non-chain result.
1447 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1449 // Emit one Select_* method for each top-level opcode. We do this instead of
1450 // emitting one giant switch statement to support compilers where this will
1451 // result in the recursive functions taking less stack space.
1452 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1453 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1454 PBOI != E; ++PBOI) {
1455 const std::string &OpName = PBOI->first;
1456 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1457 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1459 // We want to emit all of the matching code now. However, we want to emit
1460 // the matches in order of minimal cost. Sort the patterns so the least
1461 // cost one is at the start.
1462 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
1463 PatternSortingPredicate(*CGP));
1465 // Split them into groups by type.
1466 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
1467 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1468 const PatternToMatch *Pat = PatternsOfOp[i];
1469 TreePatternNode *SrcPat = Pat->getSrcPattern();
1470 MVT::ValueType VT = SrcPat->getTypeNum(0);
1471 std::map<MVT::ValueType,
1472 std::vector<const PatternToMatch*> >::iterator TI =
1473 PatternsByType.find(VT);
1474 if (TI != PatternsByType.end())
1475 TI->second.push_back(Pat);
1477 std::vector<const PatternToMatch*> PVec;
1478 PVec.push_back(Pat);
1479 PatternsByType.insert(std::make_pair(VT, PVec));
1483 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
1484 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1486 MVT::ValueType OpVT = II->first;
1487 std::vector<const PatternToMatch*> &Patterns = II->second;
1488 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1489 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1491 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1492 std::vector<std::vector<std::string> > PatternOpcodes;
1493 std::vector<std::vector<std::string> > PatternVTs;
1494 std::vector<std::set<std::string> > PatternDecls;
1495 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1496 CodeList GeneratedCode;
1497 std::set<std::string> GeneratedDecl;
1498 std::vector<std::string> TargetOpcodes;
1499 std::vector<std::string> TargetVTs;
1500 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1501 TargetOpcodes, TargetVTs);
1502 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1503 PatternDecls.push_back(GeneratedDecl);
1504 PatternOpcodes.push_back(TargetOpcodes);
1505 PatternVTs.push_back(TargetVTs);
1508 // Scan the code to see if all of the patterns are reachable and if it is
1509 // possible that the last one might not match.
1510 bool mightNotMatch = true;
1511 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1512 CodeList &GeneratedCode = CodeForPatterns[i].second;
1513 mightNotMatch = false;
1515 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1516 if (GeneratedCode[j].first == 1) { // predicate.
1517 mightNotMatch = true;
1522 // If this pattern definitely matches, and if it isn't the last one, the
1523 // patterns after it CANNOT ever match. Error out.
1524 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1525 cerr << "Pattern '";
1526 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1527 cerr << "' is impossible to select!\n";
1532 // Factor target node emission code (emitted by EmitResultCode) into
1533 // separate functions. Uniquing and share them among all instruction
1534 // selection routines.
1535 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1536 CodeList &GeneratedCode = CodeForPatterns[i].second;
1537 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1538 std::vector<std::string> &TargetVTs = PatternVTs[i];
1539 std::set<std::string> Decls = PatternDecls[i];
1540 std::vector<std::string> AddedInits;
1541 int CodeSize = (int)GeneratedCode.size();
1543 for (int j = CodeSize-1; j >= 0; --j) {
1544 if (LastPred == -1 && GeneratedCode[j].first == 1)
1546 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1547 AddedInits.push_back(GeneratedCode[j].second);
1550 std::string CalleeCode = "(const SDOperand &N";
1551 std::string CallerCode = "(N";
1552 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1553 CalleeCode += ", unsigned Opc" + utostr(j);
1554 CallerCode += ", " + TargetOpcodes[j];
1556 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1557 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1558 CallerCode += ", " + TargetVTs[j];
1560 for (std::set<std::string>::iterator
1561 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1562 std::string Name = *I;
1563 CalleeCode += ", SDOperand &" + Name;
1564 CallerCode += ", " + Name;
1568 // Prevent emission routines from being inlined to reduce selection
1569 // routines stack frame sizes.
1570 CalleeCode += "DISABLE_INLINE ";
1571 CalleeCode += "{\n";
1573 for (std::vector<std::string>::const_reverse_iterator
1574 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1575 CalleeCode += " " + *I + "\n";
1577 for (int j = LastPred+1; j < CodeSize; ++j)
1578 CalleeCode += " " + GeneratedCode[j].second + "\n";
1579 for (int j = LastPred+1; j < CodeSize; ++j)
1580 GeneratedCode.pop_back();
1581 CalleeCode += "}\n";
1583 // Uniquing the emission routines.
1584 unsigned EmitFuncNum;
1585 std::map<std::string, unsigned>::iterator EFI =
1586 EmitFunctions.find(CalleeCode);
1587 if (EFI != EmitFunctions.end()) {
1588 EmitFuncNum = EFI->second;
1590 EmitFuncNum = EmitFunctions.size();
1591 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1592 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1595 // Replace the emission code within selection routines with calls to the
1596 // emission functions.
1597 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1598 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1602 std::string OpVTStr;
1603 if (OpVT == MVT::iPTR) {
1605 } else if (OpVT == MVT::isVoid) {
1606 // Nodes with a void result actually have a first result type of either
1607 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1608 // void to this case, we handle it specially here.
1610 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1612 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1613 OpcodeVTMap.find(OpName);
1614 if (OpVTI == OpcodeVTMap.end()) {
1615 std::vector<std::string> VTSet;
1616 VTSet.push_back(OpVTStr);
1617 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1619 OpVTI->second.push_back(OpVTStr);
1621 OS << "SDNode *Select_" << getLegalCName(OpName)
1622 << OpVTStr << "(const SDOperand &N) {\n";
1624 // Loop through and reverse all of the CodeList vectors, as we will be
1625 // accessing them from their logical front, but accessing the end of a
1626 // vector is more efficient.
1627 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1628 CodeList &GeneratedCode = CodeForPatterns[i].second;
1629 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1632 // Next, reverse the list of patterns itself for the same reason.
1633 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1635 // Emit all of the patterns now, grouped together to share code.
1636 EmitPatterns(CodeForPatterns, 2, OS);
1638 // If the last pattern has predicates (which could fail) emit code to
1639 // catch the case where nothing handles a pattern.
1640 if (mightNotMatch) {
1641 OS << " cerr << \"Cannot yet select: \";\n";
1642 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1643 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1644 OpName != "ISD::INTRINSIC_VOID") {
1645 OS << " N.Val->dump(CurDAG);\n";
1647 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1648 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1649 << " cerr << \"intrinsic %\"<< "
1650 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1652 OS << " cerr << '\\n';\n"
1654 << " return NULL;\n";
1660 // Emit boilerplate.
1661 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1662 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1663 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1665 << " // Ensure that the asm operands are themselves selected.\n"
1666 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1667 << " AddToISelQueue(Ops[j]);\n\n"
1669 << " std::vector<MVT::ValueType> VTs;\n"
1670 << " VTs.push_back(MVT::Other);\n"
1671 << " VTs.push_back(MVT::Flag);\n"
1672 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1674 << " return New.Val;\n"
1677 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1678 << " SDOperand Chain = N.getOperand(0);\n"
1679 << " SDOperand N1 = N.getOperand(1);\n"
1680 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1681 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1682 << " AddToISelQueue(Chain);\n"
1683 << " SDOperand Ops[] = { Tmp, Chain };\n"
1684 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1685 << " MVT::Other, Ops, 2);\n"
1688 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1689 << " SDOperand N0 = N.getOperand(0);\n"
1690 << " SDOperand N1 = N.getOperand(1);\n"
1691 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1692 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1693 << " AddToISelQueue(N0);\n"
1694 << " SDOperand Ops[] = { N0, Tmp };\n"
1695 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1696 << " N.getValueType(), Ops, 2);\n"
1699 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1700 << " SDOperand N0 = N.getOperand(0);\n"
1701 << " SDOperand N1 = N.getOperand(1);\n"
1702 << " SDOperand N2 = N.getOperand(2);\n"
1703 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1704 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1705 << " AddToISelQueue(N1);\n"
1706 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1707 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1708 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1709 << " N.getValueType(), Ops+1, 2);\n"
1711 << " AddToISelQueue(N0);\n"
1712 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1713 << " N.getValueType(), Ops, 3);\n"
1717 OS << "// The main instruction selector code.\n"
1718 << "SDNode *SelectCode(SDOperand N) {\n"
1719 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1720 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1721 << "INSTRUCTION_LIST_END)) {\n"
1722 << " return NULL; // Already selected.\n"
1724 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1725 << " switch (N.getOpcode()) {\n"
1726 << " default: break;\n"
1727 << " case ISD::EntryToken: // These leaves remain the same.\n"
1728 << " case ISD::BasicBlock:\n"
1729 << " case ISD::Register:\n"
1730 << " case ISD::HANDLENODE:\n"
1731 << " case ISD::TargetConstant:\n"
1732 << " case ISD::TargetConstantPool:\n"
1733 << " case ISD::TargetFrameIndex:\n"
1734 << " case ISD::TargetExternalSymbol:\n"
1735 << " case ISD::TargetJumpTable:\n"
1736 << " case ISD::TargetGlobalTLSAddress:\n"
1737 << " case ISD::TargetGlobalAddress: {\n"
1738 << " return NULL;\n"
1740 << " case ISD::AssertSext:\n"
1741 << " case ISD::AssertZext: {\n"
1742 << " AddToISelQueue(N.getOperand(0));\n"
1743 << " ReplaceUses(N, N.getOperand(0));\n"
1744 << " return NULL;\n"
1746 << " case ISD::TokenFactor:\n"
1747 << " case ISD::CopyFromReg:\n"
1748 << " case ISD::CopyToReg: {\n"
1749 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1750 << " AddToISelQueue(N.getOperand(i));\n"
1751 << " return NULL;\n"
1753 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1754 << " case ISD::LABEL: return Select_LABEL(N);\n"
1755 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1756 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1759 // Loop over all of the case statements, emiting a call to each method we
1761 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1762 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1763 PBOI != E; ++PBOI) {
1764 const std::string &OpName = PBOI->first;
1765 // Potentially multiple versions of select for this opcode. One for each
1766 // ValueType of the node (or its first true operand if it doesn't produce a
1768 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1769 OpcodeVTMap.find(OpName);
1770 std::vector<std::string> &OpVTs = OpVTI->second;
1771 OS << " case " << OpName << ": {\n";
1772 // Keep track of whether we see a pattern that has an iPtr result.
1773 bool HasPtrPattern = false;
1774 bool HasDefaultPattern = false;
1776 OS << " switch (NVT) {\n";
1777 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1778 std::string &VTStr = OpVTs[i];
1779 if (VTStr.empty()) {
1780 HasDefaultPattern = true;
1784 // If this is a match on iPTR: don't emit it directly, we need special
1786 if (VTStr == "_iPTR") {
1787 HasPtrPattern = true;
1790 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1791 << " return Select_" << getLegalCName(OpName)
1792 << VTStr << "(N);\n";
1794 OS << " default:\n";
1796 // If there is an iPTR result version of this pattern, emit it here.
1797 if (HasPtrPattern) {
1798 OS << " if (NVT == TLI.getPointerTy())\n";
1799 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1801 if (HasDefaultPattern) {
1802 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1810 OS << " } // end of big switch.\n\n"
1811 << " cerr << \"Cannot yet select: \";\n"
1812 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1813 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1814 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1815 << " N.Val->dump(CurDAG);\n"
1817 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1818 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1819 << " cerr << \"intrinsic %\"<< "
1820 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1822 << " cerr << '\\n';\n"
1824 << " return NULL;\n"
1828 void DAGISelEmitter::run(std::ostream &OS) {
1829 CodeGenTarget Target;
1830 EmitSourceFileHeader("DAG Instruction Selector for the " + Target.getName() +
1833 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1834 << "// *** instruction selector class. These functions are really "
1837 OS << "#include \"llvm/Support/Compiler.h\"\n";
1839 OS << "// Instruction selector priority queue:\n"
1840 << "std::vector<SDNode*> ISelQueue;\n";
1841 OS << "/// Keep track of nodes which have already been added to queue.\n"
1842 << "unsigned char *ISelQueued;\n";
1843 OS << "/// Keep track of nodes which have already been selected.\n"
1844 << "unsigned char *ISelSelected;\n";
1845 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1846 << "std::vector<SDNode*> ISelKilled;\n\n";
1848 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1849 OS << "/// not reach Op.\n";
1850 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1851 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1852 OS << " return true;\n";
1853 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1854 OS << " return false;\n";
1855 OS << " else if (Chain->getNumOperands() > 0) {\n";
1856 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1857 OS << " if (C0.getValueType() == MVT::Other)\n";
1858 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1860 OS << " return true;\n";
1863 OS << "/// Sorting functions for the selection queue.\n"
1864 << "struct isel_sort : public std::binary_function"
1865 << "<SDNode*, SDNode*, bool> {\n"
1866 << " bool operator()(const SDNode* left, const SDNode* right) "
1868 << " return (left->getNodeId() > right->getNodeId());\n"
1872 OS << "inline void setQueued(int Id) {\n";
1873 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1875 OS << "inline bool isQueued(int Id) {\n";
1876 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1878 OS << "inline void setSelected(int Id) {\n";
1879 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1881 OS << "inline bool isSelected(int Id) {\n";
1882 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1885 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1886 OS << " int Id = N.Val->getNodeId();\n";
1887 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1888 OS << " ISelQueue.push_back(N.Val);\n";
1889 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1890 OS << " setQueued(Id);\n";
1894 OS << "inline void RemoveKilled() {\n";
1895 OS << " unsigned NumKilled = ISelKilled.size();\n";
1896 OS << " if (NumKilled) {\n";
1897 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
1898 OS << " SDNode *Temp = ISelKilled[i];\n";
1899 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
1900 << "Temp), ISelQueue.end());\n";
1902 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1903 OS << " ISelKilled.clear();\n";
1907 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
1908 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
1909 OS << " setSelected(F.Val->getNodeId());\n";
1910 OS << " RemoveKilled();\n";
1912 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
1913 OS << " unsigned FNumVals = F->getNumValues();\n";
1914 OS << " unsigned TNumVals = T->getNumValues();\n";
1915 OS << " if (FNumVals != TNumVals) {\n";
1916 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
1918 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
1919 << "SDOperand(T, i), &ISelKilled);\n";
1920 OS << " } else {\n";
1921 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
1923 OS << " setSelected(F->getNodeId());\n";
1924 OS << " RemoveKilled();\n";
1927 OS << "// SelectRoot - Top level entry to DAG isel.\n";
1928 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
1929 OS << " SelectRootInit();\n";
1930 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
1931 OS << " ISelQueued = new unsigned char[NumBytes];\n";
1932 OS << " ISelSelected = new unsigned char[NumBytes];\n";
1933 OS << " memset(ISelQueued, 0, NumBytes);\n";
1934 OS << " memset(ISelSelected, 0, NumBytes);\n";
1936 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
1937 << " // a reference to the root node, preventing it from being deleted,\n"
1938 << " // and tracking any changes of the root.\n"
1939 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
1940 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
1941 OS << " while (!ISelQueue.empty()) {\n";
1942 OS << " SDNode *Node = ISelQueue.front();\n";
1943 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1944 OS << " ISelQueue.pop_back();\n";
1945 OS << " if (!isSelected(Node->getNodeId())) {\n";
1946 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
1947 OS << " if (ResNode != Node) {\n";
1948 OS << " if (ResNode)\n";
1949 OS << " ReplaceUses(Node, ResNode);\n";
1950 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
1951 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
1952 OS << " RemoveKilled();\n";
1958 OS << " delete[] ISelQueued;\n";
1959 OS << " ISelQueued = NULL;\n";
1960 OS << " delete[] ISelSelected;\n";
1961 OS << " ISelSelected = NULL;\n";
1962 OS << " return Dummy.getValue();\n";
1965 CodegenDAGPatterns CGP(Records, OS);
1969 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
1970 for (CodegenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
1972 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
1973 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
1977 // At this point, we have full information about the 'Patterns' we need to
1978 // parse, both implicitly from instructions as well as from explicit pattern
1979 // definitions. Emit the resultant instruction selector.
1980 EmitInstructionSelector(OS);