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 Helper methods
27 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
29 static bool NodeIsComplexPattern(TreePatternNode
*N
) {
30 return (N
->isLeaf() &&
31 dynamic_cast<DefInit
*>(N
->getLeafValue()) &&
32 static_cast<DefInit
*>(N
->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
36 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
38 static const ComplexPattern
*NodeGetComplexPattern(TreePatternNode
*N
,
39 CodeGenDAGPatterns
&CGP
) {
41 dynamic_cast<DefInit
*>(N
->getLeafValue()) &&
42 static_cast<DefInit
*>(N
->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
44 return &CGP
.getComplexPattern(static_cast<DefInit
*>(N
->getLeafValue())
50 /// getPatternSize - Return the 'size' of this pattern. We want to match large
51 /// patterns before small ones. This is used to determine the size of a
53 static unsigned getPatternSize(TreePatternNode
*P
, CodeGenDAGPatterns
&CGP
) {
54 assert((MVT::isExtIntegerInVTs(P
->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P
->getExtTypes()) ||
56 P
->getExtTypeNum(0) == MVT::isVoid
||
57 P
->getExtTypeNum(0) == MVT::Flag
||
58 P
->getExtTypeNum(0) == MVT::iPTR
) &&
59 "Not a valid pattern node to size!");
60 unsigned Size
= 3; // The node itself.
61 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P
->isLeaf() && dynamic_cast<IntInit
*>(P
->getLeafValue()))
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
71 const ComplexPattern
*AM
= NodeGetComplexPattern(P
, CGP
);
73 Size
+= AM
->getNumOperands() * 3;
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P
->getPredicateFn().empty())
80 // Count children in the count if they are also nodes.
81 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
) {
82 TreePatternNode
*Child
= P
->getChild(i
);
83 if (!Child
->isLeaf() && Child
->getExtTypeNum(0) != MVT::Other
)
84 Size
+= getPatternSize(Child
, CGP
);
85 else if (Child
->isLeaf()) {
86 if (dynamic_cast<IntInit
*>(Child
->getLeafValue()))
87 Size
+= 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
88 else if (NodeIsComplexPattern(Child
))
89 Size
+= getPatternSize(Child
, CGP
);
90 else if (!Child
->getPredicateFn().empty())
98 /// getResultPatternCost - Compute the number of instructions for this pattern.
99 /// This is a temporary hack. We should really include the instruction
100 /// latencies in this calculation.
101 static unsigned getResultPatternCost(TreePatternNode
*P
,
102 CodeGenDAGPatterns
&CGP
) {
103 if (P
->isLeaf()) return 0;
106 Record
*Op
= P
->getOperator();
107 if (Op
->isSubClassOf("Instruction")) {
109 CodeGenInstruction
&II
= CGP
.getTargetInfo().getInstruction(Op
->getName());
110 if (II
.usesCustomDAGSchedInserter
)
113 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
)
114 Cost
+= getResultPatternCost(P
->getChild(i
), CGP
);
118 /// getResultPatternCodeSize - Compute the code size of instructions for this
120 static unsigned getResultPatternSize(TreePatternNode
*P
,
121 CodeGenDAGPatterns
&CGP
) {
122 if (P
->isLeaf()) return 0;
125 Record
*Op
= P
->getOperator();
126 if (Op
->isSubClassOf("Instruction")) {
127 Cost
+= Op
->getValueAsInt("CodeSize");
129 for (unsigned i
= 0, e
= P
->getNumChildren(); i
!= e
; ++i
)
130 Cost
+= getResultPatternSize(P
->getChild(i
), CGP
);
134 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135 // In particular, we want to match maximal patterns first and lowest cost within
136 // a particular complexity first.
137 struct PatternSortingPredicate
{
138 PatternSortingPredicate(CodeGenDAGPatterns
&cgp
) : CGP(cgp
) {}
139 CodeGenDAGPatterns
&CGP
;
141 bool operator()(const PatternToMatch
*LHS
,
142 const PatternToMatch
*RHS
) {
143 unsigned LHSSize
= getPatternSize(LHS
->getSrcPattern(), CGP
);
144 unsigned RHSSize
= getPatternSize(RHS
->getSrcPattern(), CGP
);
145 LHSSize
+= LHS
->getAddedComplexity();
146 RHSSize
+= RHS
->getAddedComplexity();
147 if (LHSSize
> RHSSize
) return true; // LHS -> bigger -> less cost
148 if (LHSSize
< RHSSize
) return false;
150 // If the patterns have equal complexity, compare generated instruction cost
151 unsigned LHSCost
= getResultPatternCost(LHS
->getDstPattern(), CGP
);
152 unsigned RHSCost
= getResultPatternCost(RHS
->getDstPattern(), CGP
);
153 if (LHSCost
< RHSCost
) return true;
154 if (LHSCost
> RHSCost
) return false;
156 return getResultPatternSize(LHS
->getDstPattern(), CGP
) <
157 getResultPatternSize(RHS
->getDstPattern(), CGP
);
161 /// getRegisterValueType - Look up and return the first ValueType of specified
162 /// RegisterClass record
163 static MVT::ValueType
getRegisterValueType(Record
*R
, const CodeGenTarget
&T
) {
164 if (const CodeGenRegisterClass
*RC
= T
.getRegisterClassForRegister(R
))
165 return RC
->getValueTypeNum(0);
170 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171 /// type information from it.
172 static void RemoveAllTypes(TreePatternNode
*N
) {
175 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
)
176 RemoveAllTypes(N
->getChild(i
));
179 /// NodeHasProperty - return true if TreePatternNode has the specified
181 static bool NodeHasProperty(TreePatternNode
*N
, SDNP Property
,
182 CodeGenDAGPatterns
&CGP
) {
184 const ComplexPattern
*CP
= NodeGetComplexPattern(N
, CGP
);
186 return CP
->hasProperty(Property
);
189 Record
*Operator
= N
->getOperator();
190 if (!Operator
->isSubClassOf("SDNode")) return false;
192 return CGP
.getSDNodeInfo(Operator
).hasProperty(Property
);
195 static bool PatternHasProperty(TreePatternNode
*N
, SDNP Property
,
196 CodeGenDAGPatterns
&CGP
) {
197 if (NodeHasProperty(N
, Property
, CGP
))
200 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
) {
201 TreePatternNode
*Child
= N
->getChild(i
);
202 if (PatternHasProperty(Child
, Property
, CGP
))
209 //===----------------------------------------------------------------------===//
210 // Node Transformation emitter implementation.
212 void DAGISelEmitter::EmitNodeTransforms(std::ostream
&OS
) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
215 typedef std::map
<std::string
, CodeGenDAGPatterns::NodeXForm
> NXsByNameTy
;
216 NXsByNameTy NXsByName
;
218 for (CodeGenDAGPatterns::nx_iterator I
= CGP
.nx_begin(), E
= CGP
.nx_end();
220 NXsByName
.insert(std::make_pair(I
->first
->getName(), I
->second
));
222 OS
<< "\n// Node transformations.\n";
224 for (NXsByNameTy::iterator I
= NXsByName
.begin(), E
= NXsByName
.end();
226 Record
*SDNode
= I
->second
.first
;
227 std::string Code
= I
->second
.second
;
229 if (Code
.empty()) continue; // Empty code? Skip it.
231 std::string ClassName
= CGP
.getSDNodeInfo(SDNode
).getSDClassName();
232 const char *C2
= ClassName
== "SDNode" ? "N" : "inN";
234 OS
<< "inline SDOperand Transform_" << I
->first
<< "(SDNode *" << C2
236 if (ClassName
!= "SDNode")
237 OS
<< " " << ClassName
<< " *N = cast<" << ClassName
<< ">(inN);\n";
238 OS
<< Code
<< "\n}\n";
242 //===----------------------------------------------------------------------===//
243 // Predicate emitter implementation.
246 void DAGISelEmitter::EmitPredicateFunctions(std::ostream
&OS
) {
247 OS
<< "\n// Predicate functions.\n";
249 // Walk the pattern fragments, adding them to a map, which sorts them by
251 typedef std::map
<std::string
, std::pair
<Record
*, TreePattern
*> > PFsByNameTy
;
252 PFsByNameTy PFsByName
;
254 for (CodeGenDAGPatterns::pf_iterator I
= CGP
.pf_begin(), E
= CGP
.pf_end();
256 PFsByName
.insert(std::make_pair(I
->first
->getName(), *I
));
259 for (PFsByNameTy::iterator I
= PFsByName
.begin(), E
= PFsByName
.end();
261 Record
*PatFragRecord
= I
->second
.first
;// Record that derives from PatFrag.
262 TreePattern
*P
= I
->second
.second
;
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code
= PatFragRecord
->getValueAsCode("Predicate");
266 if (Code
.empty()) continue;
268 if (P
->getOnlyTree()->isLeaf())
269 OS
<< "inline bool Predicate_" << PatFragRecord
->getName()
270 << "(SDNode *N) {\n";
272 std::string ClassName
=
273 CGP
.getSDNodeInfo(P
->getOnlyTree()->getOperator()).getSDClassName();
274 const char *C2
= ClassName
== "SDNode" ? "N" : "inN";
276 OS
<< "inline bool Predicate_" << PatFragRecord
->getName()
277 << "(SDNode *" << C2
<< ") {\n";
278 if (ClassName
!= "SDNode")
279 OS
<< " " << ClassName
<< " *N = cast<" << ClassName
<< ">(inN);\n";
281 OS
<< Code
<< "\n}\n";
288 //===----------------------------------------------------------------------===//
289 // PatternCodeEmitter implementation.
291 class PatternCodeEmitter
{
293 CodeGenDAGPatterns
&CGP
;
296 ListInit
*Predicates
;
299 // Instruction selector pattern.
300 TreePatternNode
*Pattern
;
301 // Matched instruction.
302 TreePatternNode
*Instruction
;
304 // Node to name mapping
305 std::map
<std::string
, std::string
> VariableMap
;
306 // Node to operator mapping
307 std::map
<std::string
, Record
*> OperatorMap
;
308 // Names of all the folded nodes which produce chains.
309 std::vector
<std::pair
<std::string
, unsigned> > FoldedChains
;
310 // Original input chain(s).
311 std::vector
<std::pair
<std::string
, std::string
> > OrigChains
;
312 std::set
<std::string
> Duplicates
;
314 /// GeneratedCode - This is the buffer that we emit code to. The first int
315 /// indicates whether this is an exit predicate (something that should be
316 /// tested, and if true, the match fails) [when 1], or normal code to emit
317 /// [when 0], or initialization code to emit [when 2].
318 std::vector
<std::pair
<unsigned, std::string
> > &GeneratedCode
;
319 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
320 /// the set of patterns for each top-level opcode.
321 std::set
<std::string
> &GeneratedDecl
;
322 /// TargetOpcodes - The target specific opcodes used by the resulting
324 std::vector
<std::string
> &TargetOpcodes
;
325 std::vector
<std::string
> &TargetVTs
;
327 std::string ChainName
;
332 void emitCheck(const std::string
&S
) {
334 GeneratedCode
.push_back(std::make_pair(1, S
));
336 void emitCode(const std::string
&S
) {
338 GeneratedCode
.push_back(std::make_pair(0, S
));
340 void emitInit(const std::string
&S
) {
342 GeneratedCode
.push_back(std::make_pair(2, S
));
344 void emitDecl(const std::string
&S
) {
345 assert(!S
.empty() && "Invalid declaration");
346 GeneratedDecl
.insert(S
);
348 void emitOpcode(const std::string
&Opc
) {
349 TargetOpcodes
.push_back(Opc
);
352 void emitVT(const std::string
&VT
) {
353 TargetVTs
.push_back(VT
);
357 PatternCodeEmitter(CodeGenDAGPatterns
&cgp
, ListInit
*preds
,
358 TreePatternNode
*pattern
, TreePatternNode
*instr
,
359 std::vector
<std::pair
<unsigned, std::string
> > &gc
,
360 std::set
<std::string
> &gd
,
361 std::vector
<std::string
> &to
,
362 std::vector
<std::string
> &tv
)
363 : CGP(cgp
), Predicates(preds
), Pattern(pattern
), Instruction(instr
),
364 GeneratedCode(gc
), GeneratedDecl(gd
),
365 TargetOpcodes(to
), TargetVTs(tv
),
366 TmpNo(0), OpcNo(0), VTNo(0) {}
368 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
369 /// if the match fails. At this point, we already know that the opcode for N
370 /// matches, and the SDNode for the result has the RootName specified name.
371 void EmitMatchCode(TreePatternNode
*N
, TreePatternNode
*P
,
372 const std::string
&RootName
, const std::string
&ChainSuffix
,
374 bool isRoot
= (P
== NULL
);
375 // Emit instruction predicates. Each predicate is just a string for now.
377 std::string PredicateCheck
;
378 for (unsigned i
= 0, e
= Predicates
->getSize(); i
!= e
; ++i
) {
379 if (DefInit
*Pred
= dynamic_cast<DefInit
*>(Predicates
->getElement(i
))) {
380 Record
*Def
= Pred
->getDef();
381 if (!Def
->isSubClassOf("Predicate")) {
385 assert(0 && "Unknown predicate type!");
387 if (!PredicateCheck
.empty())
388 PredicateCheck
+= " && ";
389 PredicateCheck
+= "(" + Def
->getValueAsString("CondString") + ")";
393 emitCheck(PredicateCheck
);
397 if (IntInit
*II
= dynamic_cast<IntInit
*>(N
->getLeafValue())) {
398 emitCheck("cast<ConstantSDNode>(" + RootName
+
399 ")->getSignExtended() == " + itostr(II
->getValue()));
401 } else if (!NodeIsComplexPattern(N
)) {
402 assert(0 && "Cannot match this as a leaf value!");
407 // If this node has a name associated with it, capture it in VariableMap. If
408 // we already saw this in the pattern, emit code to verify dagness.
409 if (!N
->getName().empty()) {
410 std::string
&VarMapEntry
= VariableMap
[N
->getName()];
411 if (VarMapEntry
.empty()) {
412 VarMapEntry
= RootName
;
414 // If we get here, this is a second reference to a specific name. Since
415 // we already have checked that the first reference is valid, we don't
416 // have to recursively match it, just check that it's the same as the
417 // previously named thing.
418 emitCheck(VarMapEntry
+ " == " + RootName
);
423 OperatorMap
[N
->getName()] = N
->getOperator();
427 // Emit code to load the child nodes and match their contents recursively.
429 bool NodeHasChain
= NodeHasProperty (N
, SDNPHasChain
, CGP
);
430 bool HasChain
= PatternHasProperty(N
, SDNPHasChain
, CGP
);
431 bool EmittedUseCheck
= false;
436 // Multiple uses of actual result?
437 emitCheck(RootName
+ ".hasOneUse()");
438 EmittedUseCheck
= true;
440 // If the immediate use can somehow reach this node through another
441 // path, then can't fold it either or it will create a cycle.
442 // e.g. In the following diagram, XX can reach ld through YY. If
443 // ld is folded into XX, then YY is both a predecessor and a successor
453 bool NeedCheck
= false;
457 const SDNodeInfo
&PInfo
= CGP
.getSDNodeInfo(P
->getOperator());
459 P
->getOperator() == CGP
.get_intrinsic_void_sdnode() ||
460 P
->getOperator() == CGP
.get_intrinsic_w_chain_sdnode() ||
461 P
->getOperator() == CGP
.get_intrinsic_wo_chain_sdnode() ||
462 PInfo
.getNumOperands() > 1 ||
463 PInfo
.hasProperty(SDNPHasChain
) ||
464 PInfo
.hasProperty(SDNPInFlag
) ||
465 PInfo
.hasProperty(SDNPOptInFlag
);
469 std::string
ParentName(RootName
.begin(), RootName
.end()-1);
470 emitCheck("CanBeFoldedBy(" + RootName
+ ".Val, " + ParentName
+
478 emitCheck("(" + ChainName
+ ".Val == " + RootName
+ ".Val || "
479 "IsChainCompatible(" + ChainName
+ ".Val, " +
480 RootName
+ ".Val))");
481 OrigChains
.push_back(std::make_pair(ChainName
, RootName
));
484 ChainName
= "Chain" + ChainSuffix
;
485 emitInit("SDOperand " + ChainName
+ " = " + RootName
+
490 // Don't fold any node which reads or writes a flag and has multiple uses.
491 // FIXME: We really need to separate the concepts of flag and "glue". Those
492 // real flag results, e.g. X86CMP output, can have multiple uses.
493 // FIXME: If the optional incoming flag does not exist. Then it is ok to
496 (PatternHasProperty(N
, SDNPInFlag
, CGP
) ||
497 PatternHasProperty(N
, SDNPOptInFlag
, CGP
) ||
498 PatternHasProperty(N
, SDNPOutFlag
, CGP
))) {
499 if (!EmittedUseCheck
) {
500 // Multiple uses of actual result?
501 emitCheck(RootName
+ ".hasOneUse()");
505 // If there is a node predicate for this, emit the call.
506 if (!N
->getPredicateFn().empty())
507 emitCheck(N
->getPredicateFn() + "(" + RootName
+ ".Val)");
510 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
511 // a constant without a predicate fn that has more that one bit set, handle
512 // this as a special case. This is usually for targets that have special
513 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
514 // handling stuff). Using these instructions is often far more efficient
515 // than materializing the constant. Unfortunately, both the instcombiner
516 // and the dag combiner can often infer that bits are dead, and thus drop
517 // them from the mask in the dag. For example, it might turn 'AND X, 255'
518 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
521 (N
->getOperator()->getName() == "and" ||
522 N
->getOperator()->getName() == "or") &&
523 N
->getChild(1)->isLeaf() &&
524 N
->getChild(1)->getPredicateFn().empty()) {
525 if (IntInit
*II
= dynamic_cast<IntInit
*>(N
->getChild(1)->getLeafValue())) {
526 if (!isPowerOf2_32(II
->getValue())) { // Don't bother with single bits.
527 emitInit("SDOperand " + RootName
+ "0" + " = " +
528 RootName
+ ".getOperand(" + utostr(0) + ");");
529 emitInit("SDOperand " + RootName
+ "1" + " = " +
530 RootName
+ ".getOperand(" + utostr(1) + ");");
532 emitCheck("isa<ConstantSDNode>(" + RootName
+ "1)");
533 const char *MaskPredicate
= N
->getOperator()->getName() == "or"
534 ? "CheckOrMask(" : "CheckAndMask(";
535 emitCheck(MaskPredicate
+ RootName
+ "0, cast<ConstantSDNode>(" +
536 RootName
+ "1), " + itostr(II
->getValue()) + ")");
538 EmitChildMatchCode(N
->getChild(0), N
, RootName
+ utostr(0),
539 ChainSuffix
+ utostr(0), FoundChain
);
545 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
, ++OpNo
) {
546 emitInit("SDOperand " + RootName
+ utostr(OpNo
) + " = " +
547 RootName
+ ".getOperand(" +utostr(OpNo
) + ");");
549 EmitChildMatchCode(N
->getChild(i
), N
, RootName
+ utostr(OpNo
),
550 ChainSuffix
+ utostr(OpNo
), FoundChain
);
553 // Handle cases when root is a complex pattern.
554 const ComplexPattern
*CP
;
555 if (isRoot
&& N
->isLeaf() && (CP
= NodeGetComplexPattern(N
, CGP
))) {
556 std::string Fn
= CP
->getSelectFunc();
557 unsigned NumOps
= CP
->getNumOperands();
558 for (unsigned i
= 0; i
< NumOps
; ++i
) {
559 emitDecl("CPTmp" + utostr(i
));
560 emitCode("SDOperand CPTmp" + utostr(i
) + ";");
562 if (CP
->hasProperty(SDNPHasChain
)) {
563 emitDecl("CPInChain");
564 emitDecl("Chain" + ChainSuffix
);
565 emitCode("SDOperand CPInChain;");
566 emitCode("SDOperand Chain" + ChainSuffix
+ ";");
569 std::string Code
= Fn
+ "(" + RootName
+ ", " + RootName
;
570 for (unsigned i
= 0; i
< NumOps
; i
++)
571 Code
+= ", CPTmp" + utostr(i
);
572 if (CP
->hasProperty(SDNPHasChain
)) {
573 ChainName
= "Chain" + ChainSuffix
;
574 Code
+= ", CPInChain, Chain" + ChainSuffix
;
576 emitCheck(Code
+ ")");
580 void EmitChildMatchCode(TreePatternNode
*Child
, TreePatternNode
*Parent
,
581 const std::string
&RootName
,
582 const std::string
&ChainSuffix
, bool &FoundChain
) {
583 if (!Child
->isLeaf()) {
584 // If it's not a leaf, recursively match.
585 const SDNodeInfo
&CInfo
= CGP
.getSDNodeInfo(Child
->getOperator());
586 emitCheck(RootName
+ ".getOpcode() == " +
587 CInfo
.getEnumName());
588 EmitMatchCode(Child
, Parent
, RootName
, ChainSuffix
, FoundChain
);
589 if (NodeHasProperty(Child
, SDNPHasChain
, CGP
))
590 FoldedChains
.push_back(std::make_pair(RootName
, CInfo
.getNumResults()));
592 // If this child has a name associated with it, capture it in VarMap. If
593 // we already saw this in the pattern, emit code to verify dagness.
594 if (!Child
->getName().empty()) {
595 std::string
&VarMapEntry
= VariableMap
[Child
->getName()];
596 if (VarMapEntry
.empty()) {
597 VarMapEntry
= RootName
;
599 // If we get here, this is a second reference to a specific name.
600 // Since we already have checked that the first reference is valid,
601 // we don't have to recursively match it, just check that it's the
602 // same as the previously named thing.
603 emitCheck(VarMapEntry
+ " == " + RootName
);
604 Duplicates
.insert(RootName
);
609 // Handle leaves of various types.
610 if (DefInit
*DI
= dynamic_cast<DefInit
*>(Child
->getLeafValue())) {
611 Record
*LeafRec
= DI
->getDef();
612 if (LeafRec
->isSubClassOf("RegisterClass") ||
613 LeafRec
->getName() == "ptr_rc") {
614 // Handle register references. Nothing to do here.
615 } else if (LeafRec
->isSubClassOf("Register")) {
616 // Handle register references.
617 } else if (LeafRec
->isSubClassOf("ComplexPattern")) {
618 // Handle complex pattern.
619 const ComplexPattern
*CP
= NodeGetComplexPattern(Child
, CGP
);
620 std::string Fn
= CP
->getSelectFunc();
621 unsigned NumOps
= CP
->getNumOperands();
622 for (unsigned i
= 0; i
< NumOps
; ++i
) {
623 emitDecl("CPTmp" + utostr(i
));
624 emitCode("SDOperand CPTmp" + utostr(i
) + ";");
626 if (CP
->hasProperty(SDNPHasChain
)) {
627 const SDNodeInfo
&PInfo
= CGP
.getSDNodeInfo(Parent
->getOperator());
628 FoldedChains
.push_back(std::make_pair("CPInChain",
629 PInfo
.getNumResults()));
630 ChainName
= "Chain" + ChainSuffix
;
631 emitDecl("CPInChain");
633 emitCode("SDOperand CPInChain;");
634 emitCode("SDOperand " + ChainName
+ ";");
637 std::string Code
= Fn
+ "(N, ";
638 if (CP
->hasProperty(SDNPHasChain
)) {
639 std::string
ParentName(RootName
.begin(), RootName
.end()-1);
640 Code
+= ParentName
+ ", ";
643 for (unsigned i
= 0; i
< NumOps
; i
++)
644 Code
+= ", CPTmp" + utostr(i
);
645 if (CP
->hasProperty(SDNPHasChain
))
646 Code
+= ", CPInChain, Chain" + ChainSuffix
;
647 emitCheck(Code
+ ")");
648 } else if (LeafRec
->getName() == "srcvalue") {
649 // Place holder for SRCVALUE nodes. Nothing to do here.
650 } else if (LeafRec
->isSubClassOf("ValueType")) {
651 // Make sure this is the specified value type.
652 emitCheck("cast<VTSDNode>(" + RootName
+
653 ")->getVT() == MVT::" + LeafRec
->getName());
654 } else if (LeafRec
->isSubClassOf("CondCode")) {
655 // Make sure this is the specified cond code.
656 emitCheck("cast<CondCodeSDNode>(" + RootName
+
657 ")->get() == ISD::" + LeafRec
->getName());
663 assert(0 && "Unknown leaf type!");
666 // If there is a node predicate for this, emit the call.
667 if (!Child
->getPredicateFn().empty())
668 emitCheck(Child
->getPredicateFn() + "(" + RootName
+
670 } else if (IntInit
*II
=
671 dynamic_cast<IntInit
*>(Child
->getLeafValue())) {
672 emitCheck("isa<ConstantSDNode>(" + RootName
+ ")");
673 unsigned CTmp
= TmpNo
++;
674 emitCode("int64_t CN"+utostr(CTmp
)+" = cast<ConstantSDNode>("+
675 RootName
+ ")->getSignExtended();");
677 emitCheck("CN" + utostr(CTmp
) + " == " +itostr(II
->getValue()));
682 assert(0 && "Unknown leaf type!");
687 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
688 /// we actually have to build a DAG!
689 std::vector
<std::string
>
690 EmitResultCode(TreePatternNode
*N
, std::vector
<Record
*> DstRegs
,
691 bool InFlagDecled
, bool ResNodeDecled
,
692 bool LikeLeaf
= false, bool isRoot
= false) {
693 // List of arguments of getTargetNode() or SelectNodeTo().
694 std::vector
<std::string
> NodeOps
;
695 // This is something selected from the pattern we matched.
696 if (!N
->getName().empty()) {
697 std::string
&Val
= VariableMap
[N
->getName()];
698 assert(!Val
.empty() &&
699 "Variable referenced but not defined and not caught earlier!");
700 if (Val
[0] == 'T' && Val
[1] == 'm' && Val
[2] == 'p') {
701 // Already selected this operand, just return the tmpval.
702 NodeOps
.push_back(Val
);
706 const ComplexPattern
*CP
;
707 unsigned ResNo
= TmpNo
++;
708 if (!N
->isLeaf() && N
->getOperator()->getName() == "imm") {
709 assert(N
->getExtTypes().size() == 1 && "Multiple types not handled!");
710 std::string CastType
;
711 switch (N
->getTypeNum(0)) {
713 cerr
<< "Cannot handle " << getEnumName(N
->getTypeNum(0))
714 << " type as an immediate constant. Aborting\n";
716 case MVT::i1
: CastType
= "bool"; break;
717 case MVT::i8
: CastType
= "unsigned char"; break;
718 case MVT::i16
: CastType
= "unsigned short"; break;
719 case MVT::i32
: CastType
= "unsigned"; break;
720 case MVT::i64
: CastType
= "uint64_t"; break;
722 emitCode("SDOperand Tmp" + utostr(ResNo
) +
723 " = CurDAG->getTargetConstant(((" + CastType
+
724 ") cast<ConstantSDNode>(" + Val
+ ")->getValue()), " +
725 getEnumName(N
->getTypeNum(0)) + ");");
726 NodeOps
.push_back("Tmp" + utostr(ResNo
));
727 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
728 // value if used multiple times by this pattern result.
729 Val
= "Tmp"+utostr(ResNo
);
730 } else if (!N
->isLeaf() && N
->getOperator()->getName() == "texternalsym"){
731 Record
*Op
= OperatorMap
[N
->getName()];
732 // Transform ExternalSymbol to TargetExternalSymbol
733 if (Op
&& Op
->getName() == "externalsym") {
734 emitCode("SDOperand Tmp" + utostr(ResNo
) + " = CurDAG->getTarget"
735 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
736 Val
+ ")->getSymbol(), " +
737 getEnumName(N
->getTypeNum(0)) + ");");
738 NodeOps
.push_back("Tmp" + utostr(ResNo
));
739 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
740 // this value if used multiple times by this pattern result.
741 Val
= "Tmp"+utostr(ResNo
);
743 NodeOps
.push_back(Val
);
745 } else if (!N
->isLeaf() && (N
->getOperator()->getName() == "tglobaladdr"
746 || N
->getOperator()->getName() == "tglobaltlsaddr")) {
747 Record
*Op
= OperatorMap
[N
->getName()];
748 // Transform GlobalAddress to TargetGlobalAddress
749 if (Op
&& (Op
->getName() == "globaladdr" ||
750 Op
->getName() == "globaltlsaddr")) {
751 emitCode("SDOperand Tmp" + utostr(ResNo
) + " = CurDAG->getTarget"
752 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val
+
753 ")->getGlobal(), " + getEnumName(N
->getTypeNum(0)) +
755 NodeOps
.push_back("Tmp" + utostr(ResNo
));
756 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
757 // this value if used multiple times by this pattern result.
758 Val
= "Tmp"+utostr(ResNo
);
760 NodeOps
.push_back(Val
);
762 } else if (!N
->isLeaf() && N
->getOperator()->getName() == "texternalsym"){
763 NodeOps
.push_back(Val
);
764 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
765 // value if used multiple times by this pattern result.
766 Val
= "Tmp"+utostr(ResNo
);
767 } else if (!N
->isLeaf() && N
->getOperator()->getName() == "tconstpool") {
768 NodeOps
.push_back(Val
);
769 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
770 // value if used multiple times by this pattern result.
771 Val
= "Tmp"+utostr(ResNo
);
772 } else if (N
->isLeaf() && (CP
= NodeGetComplexPattern(N
, CGP
))) {
773 for (unsigned i
= 0; i
< CP
->getNumOperands(); ++i
) {
774 emitCode("AddToISelQueue(CPTmp" + utostr(i
) + ");");
775 NodeOps
.push_back("CPTmp" + utostr(i
));
778 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
779 // node even if it isn't one. Don't select it.
781 emitCode("AddToISelQueue(" + Val
+ ");");
782 if (isRoot
&& N
->isLeaf()) {
783 emitCode("ReplaceUses(N, " + Val
+ ");");
784 emitCode("return NULL;");
787 NodeOps
.push_back(Val
);
792 // If this is an explicit register reference, handle it.
793 if (DefInit
*DI
= dynamic_cast<DefInit
*>(N
->getLeafValue())) {
794 unsigned ResNo
= TmpNo
++;
795 if (DI
->getDef()->isSubClassOf("Register")) {
796 emitCode("SDOperand Tmp" + utostr(ResNo
) + " = CurDAG->getRegister(" +
797 getQualifiedName(DI
->getDef()) + ", " +
798 getEnumName(N
->getTypeNum(0)) + ");");
799 NodeOps
.push_back("Tmp" + utostr(ResNo
));
801 } else if (DI
->getDef()->getName() == "zero_reg") {
802 emitCode("SDOperand Tmp" + utostr(ResNo
) +
803 " = CurDAG->getRegister(0, " +
804 getEnumName(N
->getTypeNum(0)) + ");");
805 NodeOps
.push_back("Tmp" + utostr(ResNo
));
808 } else if (IntInit
*II
= dynamic_cast<IntInit
*>(N
->getLeafValue())) {
809 unsigned ResNo
= TmpNo
++;
810 assert(N
->getExtTypes().size() == 1 && "Multiple types not handled!");
811 emitCode("SDOperand Tmp" + utostr(ResNo
) +
812 " = CurDAG->getTargetConstant(" + itostr(II
->getValue()) +
813 ", " + getEnumName(N
->getTypeNum(0)) + ");");
814 NodeOps
.push_back("Tmp" + utostr(ResNo
));
821 assert(0 && "Unknown leaf type!");
825 Record
*Op
= N
->getOperator();
826 if (Op
->isSubClassOf("Instruction")) {
827 const CodeGenTarget
&CGT
= CGP
.getTargetInfo();
828 CodeGenInstruction
&II
= CGT
.getInstruction(Op
->getName());
829 const DAGInstruction
&Inst
= CGP
.getInstruction(Op
);
830 const TreePattern
*InstPat
= Inst
.getPattern();
831 // FIXME: Assume actual pattern comes before "implicit".
832 TreePatternNode
*InstPatNode
=
833 isRoot
? (InstPat
? InstPat
->getTree(0) : Pattern
)
834 : (InstPat
? InstPat
->getTree(0) : NULL
);
835 if (InstPatNode
&& InstPatNode
->getOperator()->getName() == "set") {
836 InstPatNode
= InstPatNode
->getChild(InstPatNode
->getNumChildren()-1);
838 bool HasVarOps
= isRoot
&& II
.isVariadic
;
839 // FIXME: fix how we deal with physical register operands.
840 bool HasImpInputs
= isRoot
&& Inst
.getNumImpOperands() > 0;
841 bool HasImpResults
= isRoot
&& DstRegs
.size() > 0;
842 bool NodeHasOptInFlag
= isRoot
&&
843 PatternHasProperty(Pattern
, SDNPOptInFlag
, CGP
);
844 bool NodeHasInFlag
= isRoot
&&
845 PatternHasProperty(Pattern
, SDNPInFlag
, CGP
);
846 bool NodeHasOutFlag
= isRoot
&&
847 PatternHasProperty(Pattern
, SDNPOutFlag
, CGP
);
848 bool NodeHasChain
= InstPatNode
&&
849 PatternHasProperty(InstPatNode
, SDNPHasChain
, CGP
);
850 bool InputHasChain
= isRoot
&&
851 NodeHasProperty(Pattern
, SDNPHasChain
, CGP
);
852 unsigned NumResults
= Inst
.getNumResults();
853 unsigned NumDstRegs
= HasImpResults
? DstRegs
.size() : 0;
855 if (NodeHasOptInFlag
) {
856 emitCode("bool HasInFlag = "
857 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
860 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo
) + ";");
862 // How many results is this pattern expected to produce?
863 unsigned NumPatResults
= 0;
864 for (unsigned i
= 0, e
= Pattern
->getExtTypes().size(); i
!= e
; i
++) {
865 MVT::ValueType VT
= Pattern
->getTypeNum(i
);
866 if (VT
!= MVT::isVoid
&& VT
!= MVT::Flag
)
870 if (OrigChains
.size() > 0) {
871 // The original input chain is being ignored. If it is not just
872 // pointing to the op that's being folded, we should create a
873 // TokenFactor with it and the chain of the folded op as the new chain.
874 // We could potentially be doing multiple levels of folding, in that
875 // case, the TokenFactor can have more operands.
876 emitCode("SmallVector<SDOperand, 8> InChains;");
877 for (unsigned i
= 0, e
= OrigChains
.size(); i
< e
; ++i
) {
878 emitCode("if (" + OrigChains
[i
].first
+ ".Val != " +
879 OrigChains
[i
].second
+ ".Val) {");
880 emitCode(" AddToISelQueue(" + OrigChains
[i
].first
+ ");");
881 emitCode(" InChains.push_back(" + OrigChains
[i
].first
+ ");");
884 emitCode("AddToISelQueue(" + ChainName
+ ");");
885 emitCode("InChains.push_back(" + ChainName
+ ");");
886 emitCode(ChainName
+ " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
887 "&InChains[0], InChains.size());");
890 // Loop over all of the operands of the instruction pattern, emitting code
891 // to fill them all in. The node 'N' usually has number children equal to
892 // the number of input operands of the instruction. However, in cases
893 // where there are predicate operands for an instruction, we need to fill
894 // in the 'execute always' values. Match up the node operands to the
895 // instruction operands to do this.
896 std::vector
<std::string
> AllOps
;
897 unsigned NumEAInputs
= 0; // # of synthesized 'execute always' inputs.
898 for (unsigned ChildNo
= 0, InstOpNo
= NumResults
;
899 InstOpNo
!= II
.OperandList
.size(); ++InstOpNo
) {
900 std::vector
<std::string
> Ops
;
902 // If this is a normal operand or a predicate operand without
903 // 'execute always', emit it.
904 Record
*OperandNode
= II
.OperandList
[InstOpNo
].Rec
;
905 if ((!OperandNode
->isSubClassOf("PredicateOperand") &&
906 !OperandNode
->isSubClassOf("OptionalDefOperand")) ||
907 CGP
.getDefaultOperand(OperandNode
).DefaultOps
.empty()) {
908 Ops
= EmitResultCode(N
->getChild(ChildNo
), DstRegs
,
909 InFlagDecled
, ResNodeDecled
);
910 AllOps
.insert(AllOps
.end(), Ops
.begin(), Ops
.end());
913 // Otherwise, this is a predicate or optional def operand, emit the
914 // 'default ops' operands.
915 const DAGDefaultOperand
&DefaultOp
=
916 CGP
.getDefaultOperand(II
.OperandList
[InstOpNo
].Rec
);
917 for (unsigned i
= 0, e
= DefaultOp
.DefaultOps
.size(); i
!= e
; ++i
) {
918 Ops
= EmitResultCode(DefaultOp
.DefaultOps
[i
], DstRegs
,
919 InFlagDecled
, ResNodeDecled
);
920 AllOps
.insert(AllOps
.end(), Ops
.begin(), Ops
.end());
921 NumEAInputs
+= Ops
.size();
926 // Emit all the chain and CopyToReg stuff.
927 bool ChainEmitted
= NodeHasChain
;
929 emitCode("AddToISelQueue(" + ChainName
+ ");");
930 if (NodeHasInFlag
|| HasImpInputs
)
931 EmitInFlagSelectCode(Pattern
, "N", ChainEmitted
,
932 InFlagDecled
, ResNodeDecled
, true);
933 if (NodeHasOptInFlag
|| NodeHasInFlag
|| HasImpInputs
) {
935 emitCode("SDOperand InFlag(0, 0);");
938 if (NodeHasOptInFlag
) {
939 emitCode("if (HasInFlag) {");
940 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
941 emitCode(" AddToISelQueue(InFlag);");
946 unsigned ResNo
= TmpNo
++;
947 if (!isRoot
|| InputHasChain
|| NodeHasChain
|| NodeHasOutFlag
||
948 NodeHasOptInFlag
|| HasImpResults
) {
951 std::string NodeName
;
953 NodeName
= "Tmp" + utostr(ResNo
);
954 Code2
= "SDOperand " + NodeName
+ "(";
956 NodeName
= "ResNode";
957 if (!ResNodeDecled
) {
958 Code2
= "SDNode *" + NodeName
+ " = ";
959 ResNodeDecled
= true;
961 Code2
= NodeName
+ " = ";
964 Code
+= "CurDAG->getTargetNode(Opc" + utostr(OpcNo
);
965 unsigned OpsNo
= OpcNo
;
966 emitOpcode(II
.Namespace
+ "::" + II
.TheDef
->getName());
968 // Output order: results, chain, flags
970 if (NumResults
> 0 && N
->getTypeNum(0) != MVT::isVoid
) {
971 Code
+= ", VT" + utostr(VTNo
);
972 emitVT(getEnumName(N
->getTypeNum(0)));
974 // Add types for implicit results in physical registers, scheduler will
975 // care of adding copyfromreg nodes.
976 for (unsigned i
= 0; i
< NumDstRegs
; i
++) {
977 Record
*RR
= DstRegs
[i
];
978 if (RR
->isSubClassOf("Register")) {
979 MVT::ValueType RVT
= getRegisterValueType(RR
, CGT
);
980 Code
+= ", " + getEnumName(RVT
);
984 Code
+= ", MVT::Other";
986 Code
+= ", MVT::Flag";
988 // Figure out how many fixed inputs the node has. This is important to
989 // know which inputs are the variable ones if present.
990 unsigned NumInputs
= AllOps
.size();
991 NumInputs
+= NodeHasChain
;
995 for (unsigned i
= 0, e
= AllOps
.size(); i
!= e
; ++i
)
996 emitCode("Ops" + utostr(OpsNo
) + ".push_back(" + AllOps
[i
] + ");");
1001 // Figure out whether any operands at the end of the op list are not
1002 // part of the variable section.
1003 std::string EndAdjust
;
1004 if (NodeHasInFlag
|| HasImpInputs
)
1005 EndAdjust
= "-1"; // Always has one flag.
1006 else if (NodeHasOptInFlag
)
1007 EndAdjust
= "-(HasInFlag?1:0)"; // May have a flag.
1009 emitCode("for (unsigned i = " + utostr(NumInputs
- NumEAInputs
) +
1010 ", e = N.getNumOperands()" + EndAdjust
+ "; i != e; ++i) {");
1012 emitCode(" AddToISelQueue(N.getOperand(i));");
1013 emitCode(" Ops" + utostr(OpsNo
) + ".push_back(N.getOperand(i));");
1019 emitCode("Ops" + utostr(OpsNo
) + ".push_back(" + ChainName
+ ");");
1021 AllOps
.push_back(ChainName
);
1025 if (NodeHasInFlag
|| HasImpInputs
)
1026 emitCode("Ops" + utostr(OpsNo
) + ".push_back(InFlag);");
1027 else if (NodeHasOptInFlag
) {
1028 emitCode("if (HasInFlag)");
1029 emitCode(" Ops" + utostr(OpsNo
) + ".push_back(InFlag);");
1031 Code
+= ", &Ops" + utostr(OpsNo
) + "[0], Ops" + utostr(OpsNo
) +
1033 } else if (NodeHasInFlag
|| NodeHasOptInFlag
|| HasImpInputs
)
1034 AllOps
.push_back("InFlag");
1036 unsigned NumOps
= AllOps
.size();
1038 if (!NodeHasOptInFlag
&& NumOps
< 4) {
1039 for (unsigned i
= 0; i
!= NumOps
; ++i
)
1040 Code
+= ", " + AllOps
[i
];
1042 std::string OpsCode
= "SDOperand Ops" + utostr(OpsNo
) + "[] = { ";
1043 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
1044 OpsCode
+= AllOps
[i
];
1048 emitCode(OpsCode
+ " };");
1049 Code
+= ", Ops" + utostr(OpsNo
) + ", ";
1050 if (NodeHasOptInFlag
) {
1051 Code
+= "HasInFlag ? ";
1052 Code
+= utostr(NumOps
) + " : " + utostr(NumOps
-1);
1054 Code
+= utostr(NumOps
);
1060 emitCode(Code2
+ Code
+ ");");
1063 // Remember which op produces the chain.
1065 emitCode(ChainName
+ " = SDOperand(" + NodeName
+
1066 ".Val, " + utostr(NumResults
+NumDstRegs
) + ");");
1068 emitCode(ChainName
+ " = SDOperand(" + NodeName
+
1069 ", " + utostr(NumResults
+NumDstRegs
) + ");");
1072 NodeOps
.push_back("Tmp" + utostr(ResNo
));
1076 bool NeedReplace
= false;
1077 if (NodeHasOutFlag
) {
1078 if (!InFlagDecled
) {
1079 emitCode("SDOperand InFlag(ResNode, " +
1080 utostr(NumResults
+NumDstRegs
+(unsigned)NodeHasChain
) + ");");
1081 InFlagDecled
= true;
1083 emitCode("InFlag = SDOperand(ResNode, " +
1084 utostr(NumResults
+NumDstRegs
+(unsigned)NodeHasChain
) + ");");
1087 if (FoldedChains
.size() > 0) {
1089 for (unsigned j
= 0, e
= FoldedChains
.size(); j
< e
; j
++)
1090 emitCode("ReplaceUses(SDOperand(" +
1091 FoldedChains
[j
].first
+ ".Val, " +
1092 utostr(FoldedChains
[j
].second
) + "), SDOperand(ResNode, " +
1093 utostr(NumResults
+NumDstRegs
) + "));");
1097 if (NodeHasOutFlag
) {
1098 emitCode("ReplaceUses(SDOperand(N.Val, " +
1099 utostr(NumPatResults
+ (unsigned)InputHasChain
)
1104 if (NeedReplace
&& InputHasChain
)
1105 emitCode("ReplaceUses(SDOperand(N.Val, " +
1106 utostr(NumPatResults
) + "), SDOperand(" + ChainName
1107 + ".Val, " + ChainName
+ ".ResNo" + "));");
1109 // User does not expect the instruction would produce a chain!
1110 if ((!InputHasChain
&& NodeHasChain
) && NodeHasOutFlag
) {
1112 } else if (InputHasChain
&& !NodeHasChain
) {
1113 // One of the inner node produces a chain.
1115 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults
+1) +
1116 "), SDOperand(ResNode, N.ResNo-1));");
1117 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults
) +
1118 "), " + ChainName
+ ");");
1121 emitCode("return ResNode;");
1123 std::string Code
= "return CurDAG->SelectNodeTo(N.Val, Opc" +
1125 if (N
->getTypeNum(0) != MVT::isVoid
)
1126 Code
+= ", VT" + utostr(VTNo
);
1128 Code
+= ", MVT::Flag";
1130 if (NodeHasInFlag
|| NodeHasOptInFlag
|| HasImpInputs
)
1131 AllOps
.push_back("InFlag");
1133 unsigned NumOps
= AllOps
.size();
1135 if (!NodeHasOptInFlag
&& NumOps
< 4) {
1136 for (unsigned i
= 0; i
!= NumOps
; ++i
)
1137 Code
+= ", " + AllOps
[i
];
1139 std::string OpsCode
= "SDOperand Ops" + utostr(OpcNo
) + "[] = { ";
1140 for (unsigned i
= 0; i
!= NumOps
; ++i
) {
1141 OpsCode
+= AllOps
[i
];
1145 emitCode(OpsCode
+ " };");
1146 Code
+= ", Ops" + utostr(OpcNo
) + ", ";
1147 Code
+= utostr(NumOps
);
1150 emitCode(Code
+ ");");
1151 emitOpcode(II
.Namespace
+ "::" + II
.TheDef
->getName());
1152 if (N
->getTypeNum(0) != MVT::isVoid
)
1153 emitVT(getEnumName(N
->getTypeNum(0)));
1157 } else if (Op
->isSubClassOf("SDNodeXForm")) {
1158 assert(N
->getNumChildren() == 1 && "node xform should have one child!");
1159 // PatLeaf node - the operand may or may not be a leaf node. But it should
1161 std::vector
<std::string
> Ops
=
1162 EmitResultCode(N
->getChild(0), DstRegs
, InFlagDecled
,
1163 ResNodeDecled
, true);
1164 unsigned ResNo
= TmpNo
++;
1165 emitCode("SDOperand Tmp" + utostr(ResNo
) + " = Transform_" + Op
->getName()
1166 + "(" + Ops
.back() + ".Val);");
1167 NodeOps
.push_back("Tmp" + utostr(ResNo
));
1169 emitCode("return Tmp" + utostr(ResNo
) + ".Val;");
1174 throw std::string("Unknown node in result pattern!");
1178 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1179 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1180 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1181 /// for, this returns true otherwise false if Pat has all types.
1182 bool InsertOneTypeCheck(TreePatternNode
*Pat
, TreePatternNode
*Other
,
1183 const std::string
&Prefix
, bool isRoot
= false) {
1185 if (Pat
->getExtTypes() != Other
->getExtTypes()) {
1186 // Move a type over from 'other' to 'pat'.
1187 Pat
->setTypes(Other
->getExtTypes());
1188 // The top level node type is checked outside of the select function.
1190 emitCheck(Prefix
+ ".Val->getValueType(0) == " +
1191 getName(Pat
->getTypeNum(0)));
1196 (unsigned) NodeHasProperty(Pat
, SDNPHasChain
, CGP
);
1197 for (unsigned i
= 0, e
= Pat
->getNumChildren(); i
!= e
; ++i
, ++OpNo
)
1198 if (InsertOneTypeCheck(Pat
->getChild(i
), Other
->getChild(i
),
1199 Prefix
+ utostr(OpNo
)))
1205 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1207 void EmitInFlagSelectCode(TreePatternNode
*N
, const std::string
&RootName
,
1208 bool &ChainEmitted
, bool &InFlagDecled
,
1209 bool &ResNodeDecled
, bool isRoot
= false) {
1210 const CodeGenTarget
&T
= CGP
.getTargetInfo();
1212 (unsigned) NodeHasProperty(N
, SDNPHasChain
, CGP
);
1213 bool HasInFlag
= NodeHasProperty(N
, SDNPInFlag
, CGP
);
1214 for (unsigned i
= 0, e
= N
->getNumChildren(); i
!= e
; ++i
, ++OpNo
) {
1215 TreePatternNode
*Child
= N
->getChild(i
);
1216 if (!Child
->isLeaf()) {
1217 EmitInFlagSelectCode(Child
, RootName
+ utostr(OpNo
), ChainEmitted
,
1218 InFlagDecled
, ResNodeDecled
);
1220 if (DefInit
*DI
= dynamic_cast<DefInit
*>(Child
->getLeafValue())) {
1221 if (!Child
->getName().empty()) {
1222 std::string Name
= RootName
+ utostr(OpNo
);
1223 if (Duplicates
.find(Name
) != Duplicates
.end())
1224 // A duplicate! Do not emit a copy for this node.
1228 Record
*RR
= DI
->getDef();
1229 if (RR
->isSubClassOf("Register")) {
1230 MVT::ValueType RVT
= getRegisterValueType(RR
, T
);
1231 if (RVT
== MVT::Flag
) {
1232 if (!InFlagDecled
) {
1233 emitCode("SDOperand InFlag = " + RootName
+ utostr(OpNo
) + ";");
1234 InFlagDecled
= true;
1236 emitCode("InFlag = " + RootName
+ utostr(OpNo
) + ";");
1237 emitCode("AddToISelQueue(InFlag);");
1239 if (!ChainEmitted
) {
1240 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1241 ChainName
= "Chain";
1242 ChainEmitted
= true;
1244 emitCode("AddToISelQueue(" + RootName
+ utostr(OpNo
) + ");");
1245 if (!InFlagDecled
) {
1246 emitCode("SDOperand InFlag(0, 0);");
1247 InFlagDecled
= true;
1249 std::string Decl
= (!ResNodeDecled
) ? "SDNode *" : "";
1250 emitCode(Decl
+ "ResNode = CurDAG->getCopyToReg(" + ChainName
+
1251 ", " + getQualifiedName(RR
) +
1252 ", " + RootName
+ utostr(OpNo
) + ", InFlag).Val;");
1253 ResNodeDecled
= true;
1254 emitCode(ChainName
+ " = SDOperand(ResNode, 0);");
1255 emitCode("InFlag = SDOperand(ResNode, 1);");
1263 if (!InFlagDecled
) {
1264 emitCode("SDOperand InFlag = " + RootName
+
1265 ".getOperand(" + utostr(OpNo
) + ");");
1266 InFlagDecled
= true;
1268 emitCode("InFlag = " + RootName
+
1269 ".getOperand(" + utostr(OpNo
) + ");");
1270 emitCode("AddToISelQueue(InFlag);");
1275 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1276 /// stream to match the pattern, and generate the code for the match if it
1277 /// succeeds. Returns true if the pattern is not guaranteed to match.
1278 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch
&Pattern
,
1279 std::vector
<std::pair
<unsigned, std::string
> > &GeneratedCode
,
1280 std::set
<std::string
> &GeneratedDecl
,
1281 std::vector
<std::string
> &TargetOpcodes
,
1282 std::vector
<std::string
> &TargetVTs
) {
1283 PatternCodeEmitter
Emitter(CGP
, Pattern
.getPredicates(),
1284 Pattern
.getSrcPattern(), Pattern
.getDstPattern(),
1285 GeneratedCode
, GeneratedDecl
,
1286 TargetOpcodes
, TargetVTs
);
1288 // Emit the matcher, capturing named arguments in VariableMap.
1289 bool FoundChain
= false;
1290 Emitter
.EmitMatchCode(Pattern
.getSrcPattern(), NULL
, "N", "", FoundChain
);
1292 // TP - Get *SOME* tree pattern, we don't care which.
1293 TreePattern
&TP
= *CGP
.pf_begin()->second
;
1295 // At this point, we know that we structurally match the pattern, but the
1296 // types of the nodes may not match. Figure out the fewest number of type
1297 // comparisons we need to emit. For example, if there is only one integer
1298 // type supported by a target, there should be no type comparisons at all for
1299 // integer patterns!
1301 // To figure out the fewest number of type checks needed, clone the pattern,
1302 // remove the types, then perform type inference on the pattern as a whole.
1303 // If there are unresolved types, emit an explicit check for those types,
1304 // apply the type to the tree, then rerun type inference. Iterate until all
1305 // types are resolved.
1307 TreePatternNode
*Pat
= Pattern
.getSrcPattern()->clone();
1308 RemoveAllTypes(Pat
);
1311 // Resolve/propagate as many types as possible.
1313 bool MadeChange
= true;
1315 MadeChange
= Pat
->ApplyTypeConstraints(TP
,
1316 true/*Ignore reg constraints*/);
1318 assert(0 && "Error: could not find consistent types for something we"
1319 " already decided was ok!");
1323 // Insert a check for an unresolved type and add it to the tree. If we find
1324 // an unresolved type to add a check for, this returns true and we iterate,
1325 // otherwise we are done.
1326 } while (Emitter
.InsertOneTypeCheck(Pat
, Pattern
.getSrcPattern(), "N", true));
1328 Emitter
.EmitResultCode(Pattern
.getDstPattern(), Pattern
.getDstRegs(),
1329 false, false, false, true);
1333 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1334 /// a line causes any of them to be empty, remove them and return true when
1336 static bool EraseCodeLine(std::vector
<std::pair
<const PatternToMatch
*,
1337 std::vector
<std::pair
<unsigned, std::string
> > > >
1339 bool ErasedPatterns
= false;
1340 for (unsigned i
= 0, e
= Patterns
.size(); i
!= e
; ++i
) {
1341 Patterns
[i
].second
.pop_back();
1342 if (Patterns
[i
].second
.empty()) {
1343 Patterns
.erase(Patterns
.begin()+i
);
1345 ErasedPatterns
= true;
1348 return ErasedPatterns
;
1351 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1352 /// code together between the patterns.
1353 void DAGISelEmitter::EmitPatterns(std::vector
<std::pair
<const PatternToMatch
*,
1354 std::vector
<std::pair
<unsigned, std::string
> > > >
1355 &Patterns
, unsigned Indent
,
1357 typedef std::pair
<unsigned, std::string
> CodeLine
;
1358 typedef std::vector
<CodeLine
> CodeList
;
1359 typedef std::vector
<std::pair
<const PatternToMatch
*, CodeList
> > PatternList
;
1361 if (Patterns
.empty()) return;
1363 // Figure out how many patterns share the next code line. Explicitly copy
1364 // FirstCodeLine so that we don't invalidate a reference when changing
1366 const CodeLine FirstCodeLine
= Patterns
.back().second
.back();
1367 unsigned LastMatch
= Patterns
.size()-1;
1368 while (LastMatch
!= 0 && Patterns
[LastMatch
-1].second
.back() == FirstCodeLine
)
1371 // If not all patterns share this line, split the list into two pieces. The
1372 // first chunk will use this line, the second chunk won't.
1373 if (LastMatch
!= 0) {
1374 PatternList
Shared(Patterns
.begin()+LastMatch
, Patterns
.end());
1375 PatternList
Other(Patterns
.begin(), Patterns
.begin()+LastMatch
);
1377 // FIXME: Emit braces?
1378 if (Shared
.size() == 1) {
1379 const PatternToMatch
&Pattern
= *Shared
.back().first
;
1380 OS
<< "\n" << std::string(Indent
, ' ') << "// Pattern: ";
1381 Pattern
.getSrcPattern()->print(OS
);
1382 OS
<< "\n" << std::string(Indent
, ' ') << "// Emits: ";
1383 Pattern
.getDstPattern()->print(OS
);
1385 unsigned AddedComplexity
= Pattern
.getAddedComplexity();
1386 OS
<< std::string(Indent
, ' ') << "// Pattern complexity = "
1387 << getPatternSize(Pattern
.getSrcPattern(), CGP
) + AddedComplexity
1389 << getResultPatternCost(Pattern
.getDstPattern(), CGP
)
1391 << getResultPatternSize(Pattern
.getDstPattern(), CGP
) << "\n";
1393 if (FirstCodeLine
.first
!= 1) {
1394 OS
<< std::string(Indent
, ' ') << "{\n";
1397 EmitPatterns(Shared
, Indent
, OS
);
1398 if (FirstCodeLine
.first
!= 1) {
1400 OS
<< std::string(Indent
, ' ') << "}\n";
1403 if (Other
.size() == 1) {
1404 const PatternToMatch
&Pattern
= *Other
.back().first
;
1405 OS
<< "\n" << std::string(Indent
, ' ') << "// Pattern: ";
1406 Pattern
.getSrcPattern()->print(OS
);
1407 OS
<< "\n" << std::string(Indent
, ' ') << "// Emits: ";
1408 Pattern
.getDstPattern()->print(OS
);
1410 unsigned AddedComplexity
= Pattern
.getAddedComplexity();
1411 OS
<< std::string(Indent
, ' ') << "// Pattern complexity = "
1412 << getPatternSize(Pattern
.getSrcPattern(), CGP
) + AddedComplexity
1414 << getResultPatternCost(Pattern
.getDstPattern(), CGP
)
1416 << getResultPatternSize(Pattern
.getDstPattern(), CGP
) << "\n";
1418 EmitPatterns(Other
, Indent
, OS
);
1422 // Remove this code from all of the patterns that share it.
1423 bool ErasedPatterns
= EraseCodeLine(Patterns
);
1425 bool isPredicate
= FirstCodeLine
.first
== 1;
1427 // Otherwise, every pattern in the list has this line. Emit it.
1430 OS
<< std::string(Indent
, ' ') << FirstCodeLine
.second
<< "\n";
1432 OS
<< std::string(Indent
, ' ') << "if (" << FirstCodeLine
.second
;
1434 // If the next code line is another predicate, and if all of the pattern
1435 // in this group share the same next line, emit it inline now. Do this
1436 // until we run out of common predicates.
1437 while (!ErasedPatterns
&& Patterns
.back().second
.back().first
== 1) {
1438 // Check that all of fhe patterns in Patterns end with the same predicate.
1439 bool AllEndWithSamePredicate
= true;
1440 for (unsigned i
= 0, e
= Patterns
.size(); i
!= e
; ++i
)
1441 if (Patterns
[i
].second
.back() != Patterns
.back().second
.back()) {
1442 AllEndWithSamePredicate
= false;
1445 // If all of the predicates aren't the same, we can't share them.
1446 if (!AllEndWithSamePredicate
) break;
1448 // Otherwise we can. Emit it shared now.
1449 OS
<< " &&\n" << std::string(Indent
+4, ' ')
1450 << Patterns
.back().second
.back().second
;
1451 ErasedPatterns
= EraseCodeLine(Patterns
);
1458 EmitPatterns(Patterns
, Indent
, OS
);
1461 OS
<< std::string(Indent
-2, ' ') << "}\n";
1464 static std::string
getOpcodeName(Record
*Op
, CodeGenDAGPatterns
&CGP
) {
1465 return CGP
.getSDNodeInfo(Op
).getEnumName();
1468 static std::string
getLegalCName(std::string OpName
) {
1469 std::string::size_type pos
= OpName
.find("::");
1470 if (pos
!= std::string::npos
)
1471 OpName
.replace(pos
, 2, "_");
1475 void DAGISelEmitter::EmitInstructionSelector(std::ostream
&OS
) {
1476 const CodeGenTarget
&Target
= CGP
.getTargetInfo();
1478 // Get the namespace to insert instructions into. Make sure not to pick up
1479 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1480 // instruction or something.
1482 for (CodeGenTarget::inst_iterator i
= Target
.inst_begin(),
1483 e
= Target
.inst_end(); i
!= e
; ++i
) {
1484 InstNS
= i
->second
.Namespace
;
1485 if (InstNS
!= "TargetInstrInfo")
1489 if (!InstNS
.empty()) InstNS
+= "::";
1491 // Group the patterns by their top-level opcodes.
1492 std::map
<std::string
, std::vector
<const PatternToMatch
*> > PatternsByOpcode
;
1493 // All unique target node emission functions.
1494 std::map
<std::string
, unsigned> EmitFunctions
;
1495 for (CodeGenDAGPatterns::ptm_iterator I
= CGP
.ptm_begin(),
1496 E
= CGP
.ptm_end(); I
!= E
; ++I
) {
1497 const PatternToMatch
&Pattern
= *I
;
1499 TreePatternNode
*Node
= Pattern
.getSrcPattern();
1500 if (!Node
->isLeaf()) {
1501 PatternsByOpcode
[getOpcodeName(Node
->getOperator(), CGP
)].
1502 push_back(&Pattern
);
1504 const ComplexPattern
*CP
;
1505 if (dynamic_cast<IntInit
*>(Node
->getLeafValue())) {
1506 PatternsByOpcode
[getOpcodeName(CGP
.getSDNodeNamed("imm"), CGP
)].
1507 push_back(&Pattern
);
1508 } else if ((CP
= NodeGetComplexPattern(Node
, CGP
))) {
1509 std::vector
<Record
*> OpNodes
= CP
->getRootNodes();
1510 for (unsigned j
= 0, e
= OpNodes
.size(); j
!= e
; j
++) {
1511 PatternsByOpcode
[getOpcodeName(OpNodes
[j
], CGP
)]
1512 .insert(PatternsByOpcode
[getOpcodeName(OpNodes
[j
], CGP
)].begin(),
1516 cerr
<< "Unrecognized opcode '";
1518 cerr
<< "' on tree pattern '";
1519 cerr
<< Pattern
.getDstPattern()->getOperator()->getName() << "'!\n";
1525 // For each opcode, there might be multiple select functions, one per
1526 // ValueType of the node (or its first operand if it doesn't produce a
1527 // non-chain result.
1528 std::map
<std::string
, std::vector
<std::string
> > OpcodeVTMap
;
1530 // Emit one Select_* method for each top-level opcode. We do this instead of
1531 // emitting one giant switch statement to support compilers where this will
1532 // result in the recursive functions taking less stack space.
1533 for (std::map
<std::string
, std::vector
<const PatternToMatch
*> >::iterator
1534 PBOI
= PatternsByOpcode
.begin(), E
= PatternsByOpcode
.end();
1535 PBOI
!= E
; ++PBOI
) {
1536 const std::string
&OpName
= PBOI
->first
;
1537 std::vector
<const PatternToMatch
*> &PatternsOfOp
= PBOI
->second
;
1538 assert(!PatternsOfOp
.empty() && "No patterns but map has entry?");
1540 // We want to emit all of the matching code now. However, we want to emit
1541 // the matches in order of minimal cost. Sort the patterns so the least
1542 // cost one is at the start.
1543 std::stable_sort(PatternsOfOp
.begin(), PatternsOfOp
.end(),
1544 PatternSortingPredicate(CGP
));
1546 // Split them into groups by type.
1547 std::map
<MVT::ValueType
, std::vector
<const PatternToMatch
*> >PatternsByType
;
1548 for (unsigned i
= 0, e
= PatternsOfOp
.size(); i
!= e
; ++i
) {
1549 const PatternToMatch
*Pat
= PatternsOfOp
[i
];
1550 TreePatternNode
*SrcPat
= Pat
->getSrcPattern();
1551 MVT::ValueType VT
= SrcPat
->getTypeNum(0);
1552 std::map
<MVT::ValueType
,
1553 std::vector
<const PatternToMatch
*> >::iterator TI
=
1554 PatternsByType
.find(VT
);
1555 if (TI
!= PatternsByType
.end())
1556 TI
->second
.push_back(Pat
);
1558 std::vector
<const PatternToMatch
*> PVec
;
1559 PVec
.push_back(Pat
);
1560 PatternsByType
.insert(std::make_pair(VT
, PVec
));
1564 for (std::map
<MVT::ValueType
, std::vector
<const PatternToMatch
*> >::iterator
1565 II
= PatternsByType
.begin(), EE
= PatternsByType
.end(); II
!= EE
;
1567 MVT::ValueType OpVT
= II
->first
;
1568 std::vector
<const PatternToMatch
*> &Patterns
= II
->second
;
1569 typedef std::vector
<std::pair
<unsigned,std::string
> > CodeList
;
1570 typedef std::vector
<std::pair
<unsigned,std::string
> >::iterator CodeListI
;
1572 std::vector
<std::pair
<const PatternToMatch
*, CodeList
> > CodeForPatterns
;
1573 std::vector
<std::vector
<std::string
> > PatternOpcodes
;
1574 std::vector
<std::vector
<std::string
> > PatternVTs
;
1575 std::vector
<std::set
<std::string
> > PatternDecls
;
1576 for (unsigned i
= 0, e
= Patterns
.size(); i
!= e
; ++i
) {
1577 CodeList GeneratedCode
;
1578 std::set
<std::string
> GeneratedDecl
;
1579 std::vector
<std::string
> TargetOpcodes
;
1580 std::vector
<std::string
> TargetVTs
;
1581 GenerateCodeForPattern(*Patterns
[i
], GeneratedCode
, GeneratedDecl
,
1582 TargetOpcodes
, TargetVTs
);
1583 CodeForPatterns
.push_back(std::make_pair(Patterns
[i
], GeneratedCode
));
1584 PatternDecls
.push_back(GeneratedDecl
);
1585 PatternOpcodes
.push_back(TargetOpcodes
);
1586 PatternVTs
.push_back(TargetVTs
);
1589 // Scan the code to see if all of the patterns are reachable and if it is
1590 // possible that the last one might not match.
1591 bool mightNotMatch
= true;
1592 for (unsigned i
= 0, e
= CodeForPatterns
.size(); i
!= e
; ++i
) {
1593 CodeList
&GeneratedCode
= CodeForPatterns
[i
].second
;
1594 mightNotMatch
= false;
1596 for (unsigned j
= 0, e
= GeneratedCode
.size(); j
!= e
; ++j
) {
1597 if (GeneratedCode
[j
].first
== 1) { // predicate.
1598 mightNotMatch
= true;
1603 // If this pattern definitely matches, and if it isn't the last one, the
1604 // patterns after it CANNOT ever match. Error out.
1605 if (mightNotMatch
== false && i
!= CodeForPatterns
.size()-1) {
1606 cerr
<< "Pattern '";
1607 CodeForPatterns
[i
].first
->getSrcPattern()->print(*cerr
.stream());
1608 cerr
<< "' is impossible to select!\n";
1613 // Factor target node emission code (emitted by EmitResultCode) into
1614 // separate functions. Uniquing and share them among all instruction
1615 // selection routines.
1616 for (unsigned i
= 0, e
= CodeForPatterns
.size(); i
!= e
; ++i
) {
1617 CodeList
&GeneratedCode
= CodeForPatterns
[i
].second
;
1618 std::vector
<std::string
> &TargetOpcodes
= PatternOpcodes
[i
];
1619 std::vector
<std::string
> &TargetVTs
= PatternVTs
[i
];
1620 std::set
<std::string
> Decls
= PatternDecls
[i
];
1621 std::vector
<std::string
> AddedInits
;
1622 int CodeSize
= (int)GeneratedCode
.size();
1624 for (int j
= CodeSize
-1; j
>= 0; --j
) {
1625 if (LastPred
== -1 && GeneratedCode
[j
].first
== 1)
1627 else if (LastPred
!= -1 && GeneratedCode
[j
].first
== 2)
1628 AddedInits
.push_back(GeneratedCode
[j
].second
);
1631 std::string CalleeCode
= "(const SDOperand &N";
1632 std::string CallerCode
= "(N";
1633 for (unsigned j
= 0, e
= TargetOpcodes
.size(); j
!= e
; ++j
) {
1634 CalleeCode
+= ", unsigned Opc" + utostr(j
);
1635 CallerCode
+= ", " + TargetOpcodes
[j
];
1637 for (unsigned j
= 0, e
= TargetVTs
.size(); j
!= e
; ++j
) {
1638 CalleeCode
+= ", MVT::ValueType VT" + utostr(j
);
1639 CallerCode
+= ", " + TargetVTs
[j
];
1641 for (std::set
<std::string
>::iterator
1642 I
= Decls
.begin(), E
= Decls
.end(); I
!= E
; ++I
) {
1643 std::string Name
= *I
;
1644 CalleeCode
+= ", SDOperand &" + Name
;
1645 CallerCode
+= ", " + Name
;
1649 // Prevent emission routines from being inlined to reduce selection
1650 // routines stack frame sizes.
1651 CalleeCode
+= "DISABLE_INLINE ";
1652 CalleeCode
+= "{\n";
1654 for (std::vector
<std::string
>::const_reverse_iterator
1655 I
= AddedInits
.rbegin(), E
= AddedInits
.rend(); I
!= E
; ++I
)
1656 CalleeCode
+= " " + *I
+ "\n";
1658 for (int j
= LastPred
+1; j
< CodeSize
; ++j
)
1659 CalleeCode
+= " " + GeneratedCode
[j
].second
+ "\n";
1660 for (int j
= LastPred
+1; j
< CodeSize
; ++j
)
1661 GeneratedCode
.pop_back();
1662 CalleeCode
+= "}\n";
1664 // Uniquing the emission routines.
1665 unsigned EmitFuncNum
;
1666 std::map
<std::string
, unsigned>::iterator EFI
=
1667 EmitFunctions
.find(CalleeCode
);
1668 if (EFI
!= EmitFunctions
.end()) {
1669 EmitFuncNum
= EFI
->second
;
1671 EmitFuncNum
= EmitFunctions
.size();
1672 EmitFunctions
.insert(std::make_pair(CalleeCode
, EmitFuncNum
));
1673 OS
<< "SDNode *Emit_" << utostr(EmitFuncNum
) << CalleeCode
;
1676 // Replace the emission code within selection routines with calls to the
1677 // emission functions.
1678 CallerCode
= "return Emit_" + utostr(EmitFuncNum
) + CallerCode
;
1679 GeneratedCode
.push_back(std::make_pair(false, CallerCode
));
1683 std::string OpVTStr
;
1684 if (OpVT
== MVT::iPTR
) {
1686 } else if (OpVT
== MVT::isVoid
) {
1687 // Nodes with a void result actually have a first result type of either
1688 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1689 // void to this case, we handle it specially here.
1691 OpVTStr
= "_" + getEnumName(OpVT
).substr(5); // Skip 'MVT::'
1693 std::map
<std::string
, std::vector
<std::string
> >::iterator OpVTI
=
1694 OpcodeVTMap
.find(OpName
);
1695 if (OpVTI
== OpcodeVTMap
.end()) {
1696 std::vector
<std::string
> VTSet
;
1697 VTSet
.push_back(OpVTStr
);
1698 OpcodeVTMap
.insert(std::make_pair(OpName
, VTSet
));
1700 OpVTI
->second
.push_back(OpVTStr
);
1702 OS
<< "SDNode *Select_" << getLegalCName(OpName
)
1703 << OpVTStr
<< "(const SDOperand &N) {\n";
1705 // Loop through and reverse all of the CodeList vectors, as we will be
1706 // accessing them from their logical front, but accessing the end of a
1707 // vector is more efficient.
1708 for (unsigned i
= 0, e
= CodeForPatterns
.size(); i
!= e
; ++i
) {
1709 CodeList
&GeneratedCode
= CodeForPatterns
[i
].second
;
1710 std::reverse(GeneratedCode
.begin(), GeneratedCode
.end());
1713 // Next, reverse the list of patterns itself for the same reason.
1714 std::reverse(CodeForPatterns
.begin(), CodeForPatterns
.end());
1716 // Emit all of the patterns now, grouped together to share code.
1717 EmitPatterns(CodeForPatterns
, 2, OS
);
1719 // If the last pattern has predicates (which could fail) emit code to
1720 // catch the case where nothing handles a pattern.
1721 if (mightNotMatch
) {
1722 OS
<< " cerr << \"Cannot yet select: \";\n";
1723 if (OpName
!= "ISD::INTRINSIC_W_CHAIN" &&
1724 OpName
!= "ISD::INTRINSIC_WO_CHAIN" &&
1725 OpName
!= "ISD::INTRINSIC_VOID") {
1726 OS
<< " N.Val->dump(CurDAG);\n";
1728 OS
<< " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1729 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1730 << " cerr << \"intrinsic %\"<< "
1731 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1733 OS
<< " cerr << '\\n';\n"
1735 << " return NULL;\n";
1741 // Emit boilerplate.
1742 OS
<< "SDNode *Select_INLINEASM(SDOperand N) {\n"
1743 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1744 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1746 << " // Ensure that the asm operands are themselves selected.\n"
1747 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1748 << " AddToISelQueue(Ops[j]);\n\n"
1750 << " std::vector<MVT::ValueType> VTs;\n"
1751 << " VTs.push_back(MVT::Other);\n"
1752 << " VTs.push_back(MVT::Flag);\n"
1753 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1755 << " return New.Val;\n"
1758 OS
<< "SDNode *Select_LABEL(const SDOperand &N) {\n"
1759 << " SDOperand Chain = N.getOperand(0);\n"
1760 << " SDOperand N1 = N.getOperand(1);\n"
1761 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1762 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1763 << " AddToISelQueue(Chain);\n"
1764 << " SDOperand Ops[] = { Tmp, Chain };\n"
1765 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
1766 << " MVT::Other, Ops, 2);\n"
1769 OS
<< "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1770 << " SDOperand N0 = N.getOperand(0);\n"
1771 << " SDOperand N1 = N.getOperand(1);\n"
1772 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1773 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1774 << " AddToISelQueue(N0);\n"
1775 << " SDOperand Ops[] = { N0, Tmp };\n"
1776 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
1777 << " N.getValueType(), Ops, 2);\n"
1780 OS
<< "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1781 << " SDOperand N0 = N.getOperand(0);\n"
1782 << " SDOperand N1 = N.getOperand(1);\n"
1783 << " SDOperand N2 = N.getOperand(2);\n"
1784 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1785 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1786 << " AddToISelQueue(N1);\n"
1787 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
1788 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
1789 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1790 << " N.getValueType(), Ops+1, 2);\n"
1792 << " AddToISelQueue(N0);\n"
1793 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
1794 << " N.getValueType(), Ops, 3);\n"
1798 OS
<< "// The main instruction selector code.\n"
1799 << "SDNode *SelectCode(SDOperand N) {\n"
1800 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1801 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1802 << "INSTRUCTION_LIST_END)) {\n"
1803 << " return NULL; // Already selected.\n"
1805 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1806 << " switch (N.getOpcode()) {\n"
1807 << " default: break;\n"
1808 << " case ISD::EntryToken: // These leaves remain the same.\n"
1809 << " case ISD::BasicBlock:\n"
1810 << " case ISD::Register:\n"
1811 << " case ISD::HANDLENODE:\n"
1812 << " case ISD::TargetConstant:\n"
1813 << " case ISD::TargetConstantPool:\n"
1814 << " case ISD::TargetFrameIndex:\n"
1815 << " case ISD::TargetExternalSymbol:\n"
1816 << " case ISD::TargetJumpTable:\n"
1817 << " case ISD::TargetGlobalTLSAddress:\n"
1818 << " case ISD::TargetGlobalAddress: {\n"
1819 << " return NULL;\n"
1821 << " case ISD::AssertSext:\n"
1822 << " case ISD::AssertZext: {\n"
1823 << " AddToISelQueue(N.getOperand(0));\n"
1824 << " ReplaceUses(N, N.getOperand(0));\n"
1825 << " return NULL;\n"
1827 << " case ISD::TokenFactor:\n"
1828 << " case ISD::CopyFromReg:\n"
1829 << " case ISD::CopyToReg: {\n"
1830 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1831 << " AddToISelQueue(N.getOperand(i));\n"
1832 << " return NULL;\n"
1834 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1835 << " case ISD::LABEL: return Select_LABEL(N);\n"
1836 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1837 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
1840 // Loop over all of the case statements, emiting a call to each method we
1842 for (std::map
<std::string
, std::vector
<const PatternToMatch
*> >::iterator
1843 PBOI
= PatternsByOpcode
.begin(), E
= PatternsByOpcode
.end();
1844 PBOI
!= E
; ++PBOI
) {
1845 const std::string
&OpName
= PBOI
->first
;
1846 // Potentially multiple versions of select for this opcode. One for each
1847 // ValueType of the node (or its first true operand if it doesn't produce a
1849 std::map
<std::string
, std::vector
<std::string
> >::iterator OpVTI
=
1850 OpcodeVTMap
.find(OpName
);
1851 std::vector
<std::string
> &OpVTs
= OpVTI
->second
;
1852 OS
<< " case " << OpName
<< ": {\n";
1853 // Keep track of whether we see a pattern that has an iPtr result.
1854 bool HasPtrPattern
= false;
1855 bool HasDefaultPattern
= false;
1857 OS
<< " switch (NVT) {\n";
1858 for (unsigned i
= 0, e
= OpVTs
.size(); i
< e
; ++i
) {
1859 std::string
&VTStr
= OpVTs
[i
];
1860 if (VTStr
.empty()) {
1861 HasDefaultPattern
= true;
1865 // If this is a match on iPTR: don't emit it directly, we need special
1867 if (VTStr
== "_iPTR") {
1868 HasPtrPattern
= true;
1871 OS
<< " case MVT::" << VTStr
.substr(1) << ":\n"
1872 << " return Select_" << getLegalCName(OpName
)
1873 << VTStr
<< "(N);\n";
1875 OS
<< " default:\n";
1877 // If there is an iPTR result version of this pattern, emit it here.
1878 if (HasPtrPattern
) {
1879 OS
<< " if (NVT == TLI.getPointerTy())\n";
1880 OS
<< " return Select_" << getLegalCName(OpName
) <<"_iPTR(N);\n";
1882 if (HasDefaultPattern
) {
1883 OS
<< " return Select_" << getLegalCName(OpName
) << "(N);\n";
1891 OS
<< " } // end of big switch.\n\n"
1892 << " cerr << \"Cannot yet select: \";\n"
1893 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1894 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1895 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1896 << " N.Val->dump(CurDAG);\n"
1898 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1899 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1900 << " cerr << \"intrinsic %\"<< "
1901 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1903 << " cerr << '\\n';\n"
1905 << " return NULL;\n"
1909 void DAGISelEmitter::run(std::ostream
&OS
) {
1910 EmitSourceFileHeader("DAG Instruction Selector for the " +
1911 CGP
.getTargetInfo().getName() + " target", OS
);
1913 OS
<< "// *** NOTE: This file is #included into the middle of the target\n"
1914 << "// *** instruction selector class. These functions are really "
1917 OS
<< "#include \"llvm/Support/Compiler.h\"\n";
1919 OS
<< "// Instruction selector priority queue:\n"
1920 << "std::vector<SDNode*> ISelQueue;\n";
1921 OS
<< "/// Keep track of nodes which have already been added to queue.\n"
1922 << "unsigned char *ISelQueued;\n";
1923 OS
<< "/// Keep track of nodes which have already been selected.\n"
1924 << "unsigned char *ISelSelected;\n";
1925 OS
<< "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1926 << "std::vector<SDNode*> ISelKilled;\n\n";
1928 OS
<< "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1929 OS
<< "/// not reach Op.\n";
1930 OS
<< "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1931 OS
<< " if (Chain->getOpcode() == ISD::EntryToken)\n";
1932 OS
<< " return true;\n";
1933 OS
<< " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1934 OS
<< " return false;\n";
1935 OS
<< " else if (Chain->getNumOperands() > 0) {\n";
1936 OS
<< " SDOperand C0 = Chain->getOperand(0);\n";
1937 OS
<< " if (C0.getValueType() == MVT::Other)\n";
1938 OS
<< " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1940 OS
<< " return true;\n";
1943 OS
<< "/// Sorting functions for the selection queue.\n"
1944 << "struct isel_sort : public std::binary_function"
1945 << "<SDNode*, SDNode*, bool> {\n"
1946 << " bool operator()(const SDNode* left, const SDNode* right) "
1948 << " return (left->getNodeId() > right->getNodeId());\n"
1952 OS
<< "inline void setQueued(int Id) {\n";
1953 OS
<< " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1955 OS
<< "inline bool isQueued(int Id) {\n";
1956 OS
<< " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1958 OS
<< "inline void setSelected(int Id) {\n";
1959 OS
<< " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1961 OS
<< "inline bool isSelected(int Id) {\n";
1962 OS
<< " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1965 OS
<< "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
1966 OS
<< " int Id = N.Val->getNodeId();\n";
1967 OS
<< " if (Id != -1 && !isQueued(Id)) {\n";
1968 OS
<< " ISelQueue.push_back(N.Val);\n";
1969 OS
<< " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1970 OS
<< " setQueued(Id);\n";
1974 OS
<< "inline void RemoveKilled() {\n";
1975 OS
<< " unsigned NumKilled = ISelKilled.size();\n";
1976 OS
<< " if (NumKilled) {\n";
1977 OS
<< " for (unsigned i = 0; i != NumKilled; ++i) {\n";
1978 OS
<< " SDNode *Temp = ISelKilled[i];\n";
1979 OS
<< " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
1980 << "Temp), ISelQueue.end());\n";
1982 OS
<< " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1983 OS
<< " ISelKilled.clear();\n";
1987 OS
<< "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
1988 OS
<< " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
1989 OS
<< " setSelected(F.Val->getNodeId());\n";
1990 OS
<< " RemoveKilled();\n";
1992 OS
<< "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
1993 OS
<< " unsigned FNumVals = F->getNumValues();\n";
1994 OS
<< " unsigned TNumVals = T->getNumValues();\n";
1995 OS
<< " if (FNumVals != TNumVals) {\n";
1996 OS
<< " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
1998 OS
<< " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
1999 << "SDOperand(T, i), &ISelKilled);\n";
2000 OS
<< " } else {\n";
2001 OS
<< " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2003 OS
<< " setSelected(F->getNodeId());\n";
2004 OS
<< " RemoveKilled();\n";
2007 OS
<< "// SelectRoot - Top level entry to DAG isel.\n";
2008 OS
<< "SDOperand SelectRoot(SDOperand Root) {\n";
2009 OS
<< " SelectRootInit();\n";
2010 OS
<< " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2011 OS
<< " ISelQueued = new unsigned char[NumBytes];\n";
2012 OS
<< " ISelSelected = new unsigned char[NumBytes];\n";
2013 OS
<< " memset(ISelQueued, 0, NumBytes);\n";
2014 OS
<< " memset(ISelSelected, 0, NumBytes);\n";
2016 OS
<< " // Create a dummy node (which is not added to allnodes), that adds\n"
2017 << " // a reference to the root node, preventing it from being deleted,\n"
2018 << " // and tracking any changes of the root.\n"
2019 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2020 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2021 OS
<< " while (!ISelQueue.empty()) {\n";
2022 OS
<< " SDNode *Node = ISelQueue.front();\n";
2023 OS
<< " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2024 OS
<< " ISelQueue.pop_back();\n";
2025 OS
<< " if (!isSelected(Node->getNodeId())) {\n";
2026 OS
<< " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2027 OS
<< " if (ResNode != Node) {\n";
2028 OS
<< " if (ResNode)\n";
2029 OS
<< " ReplaceUses(Node, ResNode);\n";
2030 OS
<< " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2031 OS
<< " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2032 OS
<< " RemoveKilled();\n";
2038 OS
<< " delete[] ISelQueued;\n";
2039 OS
<< " ISelQueued = NULL;\n";
2040 OS
<< " delete[] ISelSelected;\n";
2041 OS
<< " ISelSelected = NULL;\n";
2042 OS
<< " return Dummy.getValue();\n";
2045 EmitNodeTransforms(OS
);
2046 EmitPredicateFunctions(OS
);
2048 DOUT
<< "\n\nALL PATTERNS TO MATCH:\n\n";
2049 for (CodeGenDAGPatterns::ptm_iterator I
= CGP
.ptm_begin(), E
= CGP
.ptm_end();
2051 DOUT
<< "PATTERN: "; DEBUG(I
->getSrcPattern()->dump());
2052 DOUT
<< "\nRESULT: "; DEBUG(I
->getDstPattern()->dump());
2056 // At this point, we have full information about the 'Patterns' we need to
2057 // parse, both implicitly from instructions as well as from explicit pattern
2058 // definitions. Emit the resultant instruction selector.
2059 EmitInstructionSelector(OS
);