Reference to hidden symbols do not have to go through non-lazy pointer in non-pic...
[llvm/avr.git] / utils / TableGen / DAGISelEmitter.cpp
blob95df746aecd9788e140f8e8c1732de54b9cdc19a
1 //===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #include "DAGISelEmitter.h"
15 #include "Record.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/Support/CommandLine.h"
18 #include "llvm/Support/Debug.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Support/Debug.h"
21 #include <algorithm>
22 #include <deque>
23 #include <iostream>
24 using namespace llvm;
26 static cl::opt<bool>
27 GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
29 //===----------------------------------------------------------------------===//
30 // DAGISelEmitter Helper methods
33 /// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
34 /// ComplexPattern.
35 static bool NodeIsComplexPattern(TreePatternNode *N) {
36 return (N->isLeaf() &&
37 dynamic_cast<DefInit*>(N->getLeafValue()) &&
38 static_cast<DefInit*>(N->getLeafValue())->getDef()->
39 isSubClassOf("ComplexPattern"));
42 /// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
43 /// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
44 static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
45 CodeGenDAGPatterns &CGP) {
46 if (N->isLeaf() &&
47 dynamic_cast<DefInit*>(N->getLeafValue()) &&
48 static_cast<DefInit*>(N->getLeafValue())->getDef()->
49 isSubClassOf("ComplexPattern")) {
50 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
51 ->getDef());
53 return NULL;
56 /// getPatternSize - Return the 'size' of this pattern. We want to match large
57 /// patterns before small ones. This is used to determine the size of a
58 /// pattern.
59 static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
60 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
61 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
62 P->getExtTypeNum(0) == MVT::isVoid ||
63 P->getExtTypeNum(0) == MVT::Flag ||
64 P->getExtTypeNum(0) == MVT::iPTR ||
65 P->getExtTypeNum(0) == MVT::iPTRAny) &&
66 "Not a valid pattern node to size!");
67 unsigned Size = 3; // The node itself.
68 // If the root node is a ConstantSDNode, increases its size.
69 // e.g. (set R32:$dst, 0).
70 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
71 Size += 2;
73 // FIXME: This is a hack to statically increase the priority of patterns
74 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
75 // Later we can allow complexity / cost for each pattern to be (optionally)
76 // specified. To get best possible pattern match we'll need to dynamically
77 // calculate the complexity of all patterns a dag can potentially map to.
78 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
79 if (AM)
80 Size += AM->getNumOperands() * 3;
82 // If this node has some predicate function that must match, it adds to the
83 // complexity of this node.
84 if (!P->getPredicateFns().empty())
85 ++Size;
87 // Count children in the count if they are also nodes.
88 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
89 TreePatternNode *Child = P->getChild(i);
90 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
91 Size += getPatternSize(Child, CGP);
92 else if (Child->isLeaf()) {
93 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
94 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
95 else if (NodeIsComplexPattern(Child))
96 Size += getPatternSize(Child, CGP);
97 else if (!Child->getPredicateFns().empty())
98 ++Size;
102 return Size;
105 /// getResultPatternCost - Compute the number of instructions for this pattern.
106 /// This is a temporary hack. We should really include the instruction
107 /// latencies in this calculation.
108 static unsigned getResultPatternCost(TreePatternNode *P,
109 CodeGenDAGPatterns &CGP) {
110 if (P->isLeaf()) return 0;
112 unsigned Cost = 0;
113 Record *Op = P->getOperator();
114 if (Op->isSubClassOf("Instruction")) {
115 Cost++;
116 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
117 if (II.usesCustomDAGSchedInserter)
118 Cost += 10;
120 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
121 Cost += getResultPatternCost(P->getChild(i), CGP);
122 return Cost;
125 /// getResultPatternCodeSize - Compute the code size of instructions for this
126 /// pattern.
127 static unsigned getResultPatternSize(TreePatternNode *P,
128 CodeGenDAGPatterns &CGP) {
129 if (P->isLeaf()) return 0;
131 unsigned Cost = 0;
132 Record *Op = P->getOperator();
133 if (Op->isSubClassOf("Instruction")) {
134 Cost += Op->getValueAsInt("CodeSize");
136 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
137 Cost += getResultPatternSize(P->getChild(i), CGP);
138 return Cost;
141 // PatternSortingPredicate - return true if we prefer to match LHS before RHS.
142 // In particular, we want to match maximal patterns first and lowest cost within
143 // a particular complexity first.
144 struct PatternSortingPredicate {
145 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
146 CodeGenDAGPatterns &CGP;
148 typedef std::pair<unsigned, std::string> CodeLine;
149 typedef std::vector<CodeLine> CodeList;
150 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
152 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
153 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
154 const PatternToMatch *LHS = LHSPair.first;
155 const PatternToMatch *RHS = RHSPair.first;
157 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
158 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
159 LHSSize += LHS->getAddedComplexity();
160 RHSSize += RHS->getAddedComplexity();
161 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
162 if (LHSSize < RHSSize) return false;
164 // If the patterns have equal complexity, compare generated instruction cost
165 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
166 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
167 if (LHSCost < RHSCost) return true;
168 if (LHSCost > RHSCost) return false;
170 return getResultPatternSize(LHS->getDstPattern(), CGP) <
171 getResultPatternSize(RHS->getDstPattern(), CGP);
175 /// getRegisterValueType - Look up and return the ValueType of the specified
176 /// register. If the register is a member of multiple register classes which
177 /// have different associated types, return MVT::Other.
178 static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
179 bool FoundRC = false;
180 MVT::SimpleValueType VT = MVT::Other;
181 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
182 std::vector<CodeGenRegisterClass>::const_iterator RC;
183 std::vector<Record*>::const_iterator Element;
185 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
186 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
187 if (Element != (*RC).Elements.end()) {
188 if (!FoundRC) {
189 FoundRC = true;
190 VT = (*RC).getValueTypeNum(0);
191 } else {
192 // In multiple RC's
193 if (VT != (*RC).getValueTypeNum(0)) {
194 // Types of the RC's do not agree. Return MVT::Other. The
195 // target is responsible for handling this.
196 return MVT::Other;
201 return VT;
205 /// RemoveAllTypes - A quick recursive walk over a pattern which removes all
206 /// type information from it.
207 static void RemoveAllTypes(TreePatternNode *N) {
208 N->removeTypes();
209 if (!N->isLeaf())
210 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
211 RemoveAllTypes(N->getChild(i));
214 /// NodeHasProperty - return true if TreePatternNode has the specified
215 /// property.
216 static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
217 CodeGenDAGPatterns &CGP) {
218 if (N->isLeaf()) {
219 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
220 if (CP)
221 return CP->hasProperty(Property);
222 return false;
224 Record *Operator = N->getOperator();
225 if (!Operator->isSubClassOf("SDNode")) return false;
227 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
230 static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
231 CodeGenDAGPatterns &CGP) {
232 if (NodeHasProperty(N, Property, CGP))
233 return true;
235 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
236 TreePatternNode *Child = N->getChild(i);
237 if (PatternHasProperty(Child, Property, CGP))
238 return true;
241 return false;
244 static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
245 return CGP.getSDNodeInfo(Op).getEnumName();
248 static
249 bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
250 bool isStore = !N->isLeaf() &&
251 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
252 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
253 return false;
255 bool HasChain = false;
256 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
257 TreePatternNode *Child = N->getChild(i);
258 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
259 HasChain = true;
260 break;
263 return HasChain;
266 //===----------------------------------------------------------------------===//
267 // Node Transformation emitter implementation.
269 void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
270 // Walk the pattern fragments, adding them to a map, which sorts them by
271 // name.
272 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
273 NXsByNameTy NXsByName;
275 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
276 I != E; ++I)
277 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
279 OS << "\n// Node transformations.\n";
281 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
282 I != E; ++I) {
283 Record *SDNode = I->second.first;
284 std::string Code = I->second.second;
286 if (Code.empty()) continue; // Empty code? Skip it.
288 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
289 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
291 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
292 << ") {\n";
293 if (ClassName != "SDNode")
294 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
295 OS << Code << "\n}\n";
299 //===----------------------------------------------------------------------===//
300 // Predicate emitter implementation.
303 void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
304 OS << "\n// Predicate functions.\n";
306 // Walk the pattern fragments, adding them to a map, which sorts them by
307 // name.
308 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
309 PFsByNameTy PFsByName;
311 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
312 I != E; ++I)
313 PFsByName.insert(std::make_pair(I->first->getName(), *I));
316 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
317 I != E; ++I) {
318 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
319 TreePattern *P = I->second.second;
321 // If there is a code init for this fragment, emit the predicate code.
322 std::string Code = PatFragRecord->getValueAsCode("Predicate");
323 if (Code.empty()) continue;
325 if (P->getOnlyTree()->isLeaf())
326 OS << "inline bool Predicate_" << PatFragRecord->getName()
327 << "(SDNode *N) {\n";
328 else {
329 std::string ClassName =
330 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
331 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
333 OS << "inline bool Predicate_" << PatFragRecord->getName()
334 << "(SDNode *" << C2 << ") {\n";
335 if (ClassName != "SDNode")
336 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
338 OS << Code << "\n}\n";
341 OS << "\n\n";
345 //===----------------------------------------------------------------------===//
346 // PatternCodeEmitter implementation.
348 class PatternCodeEmitter {
349 private:
350 CodeGenDAGPatterns &CGP;
352 // Predicates.
353 std::string PredicateCheck;
354 // Pattern cost.
355 unsigned Cost;
356 // Instruction selector pattern.
357 TreePatternNode *Pattern;
358 // Matched instruction.
359 TreePatternNode *Instruction;
361 // Node to name mapping
362 std::map<std::string, std::string> VariableMap;
363 // Node to operator mapping
364 std::map<std::string, Record*> OperatorMap;
365 // Name of the folded node which produces a flag.
366 std::pair<std::string, unsigned> FoldedFlag;
367 // Names of all the folded nodes which produce chains.
368 std::vector<std::pair<std::string, unsigned> > FoldedChains;
369 // Original input chain(s).
370 std::vector<std::pair<std::string, std::string> > OrigChains;
371 std::set<std::string> Duplicates;
373 /// LSI - Load/Store information.
374 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
375 /// for each memory access. This facilitates the use of AliasAnalysis in
376 /// the backend.
377 std::vector<std::string> LSI;
379 /// GeneratedCode - This is the buffer that we emit code to. The first int
380 /// indicates whether this is an exit predicate (something that should be
381 /// tested, and if true, the match fails) [when 1], or normal code to emit
382 /// [when 0], or initialization code to emit [when 2].
383 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
384 /// GeneratedDecl - This is the set of all SDValue declarations needed for
385 /// the set of patterns for each top-level opcode.
386 std::set<std::string> &GeneratedDecl;
387 /// TargetOpcodes - The target specific opcodes used by the resulting
388 /// instructions.
389 std::vector<std::string> &TargetOpcodes;
390 std::vector<std::string> &TargetVTs;
391 /// OutputIsVariadic - Records whether the instruction output pattern uses
392 /// variable_ops. This requires that the Emit function be passed an
393 /// additional argument to indicate where the input varargs operands
394 /// begin.
395 bool &OutputIsVariadic;
396 /// NumInputRootOps - Records the number of operands the root node of the
397 /// input pattern has. This information is used in the generated code to
398 /// pass to Emit functions when variable_ops processing is needed.
399 unsigned &NumInputRootOps;
401 std::string ChainName;
402 unsigned TmpNo;
403 unsigned OpcNo;
404 unsigned VTNo;
406 void emitCheck(const std::string &S) {
407 if (!S.empty())
408 GeneratedCode.push_back(std::make_pair(1, S));
410 void emitCode(const std::string &S) {
411 if (!S.empty())
412 GeneratedCode.push_back(std::make_pair(0, S));
414 void emitInit(const std::string &S) {
415 if (!S.empty())
416 GeneratedCode.push_back(std::make_pair(2, S));
418 void emitDecl(const std::string &S) {
419 assert(!S.empty() && "Invalid declaration");
420 GeneratedDecl.insert(S);
422 void emitOpcode(const std::string &Opc) {
423 TargetOpcodes.push_back(Opc);
424 OpcNo++;
426 void emitVT(const std::string &VT) {
427 TargetVTs.push_back(VT);
428 VTNo++;
430 public:
431 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
432 TreePatternNode *pattern, TreePatternNode *instr,
433 std::vector<std::pair<unsigned, std::string> > &gc,
434 std::set<std::string> &gd,
435 std::vector<std::string> &to,
436 std::vector<std::string> &tv,
437 bool &oiv,
438 unsigned &niro)
439 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
440 GeneratedCode(gc), GeneratedDecl(gd),
441 TargetOpcodes(to), TargetVTs(tv),
442 OutputIsVariadic(oiv), NumInputRootOps(niro),
443 TmpNo(0), OpcNo(0), VTNo(0) {}
445 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
446 /// if the match fails. At this point, we already know that the opcode for N
447 /// matches, and the SDNode for the result has the RootName specified name.
448 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
449 const std::string &RootName, const std::string &ChainSuffix,
450 bool &FoundChain) {
452 // Save loads/stores matched by a pattern.
453 if (!N->isLeaf() && N->getName().empty()) {
454 if (NodeHasProperty(N, SDNPMemOperand, CGP))
455 LSI.push_back(RootName);
458 bool isRoot = (P == NULL);
459 // Emit instruction predicates. Each predicate is just a string for now.
460 if (isRoot) {
461 // Record input varargs info.
462 NumInputRootOps = N->getNumChildren();
464 if (DisablePatternForFastISel(N, CGP))
465 emitCheck("OptLevel != CodeGenOpt::None");
467 emitCheck(PredicateCheck);
470 if (N->isLeaf()) {
471 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
472 emitCheck("cast<ConstantSDNode>(" + RootName +
473 ")->getSExtValue() == INT64_C(" +
474 itostr(II->getValue()) + ")");
475 return;
476 } else if (!NodeIsComplexPattern(N)) {
477 assert(0 && "Cannot match this as a leaf value!");
478 abort();
482 // If this node has a name associated with it, capture it in VariableMap. If
483 // we already saw this in the pattern, emit code to verify dagness.
484 if (!N->getName().empty()) {
485 std::string &VarMapEntry = VariableMap[N->getName()];
486 if (VarMapEntry.empty()) {
487 VarMapEntry = RootName;
488 } else {
489 // If we get here, this is a second reference to a specific name. Since
490 // we already have checked that the first reference is valid, we don't
491 // have to recursively match it, just check that it's the same as the
492 // previously named thing.
493 emitCheck(VarMapEntry + " == " + RootName);
494 return;
497 if (!N->isLeaf())
498 OperatorMap[N->getName()] = N->getOperator();
502 // Emit code to load the child nodes and match their contents recursively.
503 unsigned OpNo = 0;
504 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
505 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
506 bool EmittedUseCheck = false;
507 if (HasChain) {
508 if (NodeHasChain)
509 OpNo = 1;
510 if (!isRoot) {
511 // Multiple uses of actual result?
512 emitCheck(RootName + ".hasOneUse()");
513 EmittedUseCheck = true;
514 if (NodeHasChain) {
515 // If the immediate use can somehow reach this node through another
516 // path, then can't fold it either or it will create a cycle.
517 // e.g. In the following diagram, XX can reach ld through YY. If
518 // ld is folded into XX, then YY is both a predecessor and a successor
519 // of XX.
521 // [ld]
522 // ^ ^
523 // | |
524 // / \---
525 // / [YY]
526 // | ^
527 // [XX]-------|
528 bool NeedCheck = P != Pattern;
529 if (!NeedCheck) {
530 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
531 NeedCheck =
532 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
533 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
534 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
535 PInfo.getNumOperands() > 1 ||
536 PInfo.hasProperty(SDNPHasChain) ||
537 PInfo.hasProperty(SDNPInFlag) ||
538 PInfo.hasProperty(SDNPOptInFlag);
541 if (NeedCheck) {
542 std::string ParentName(RootName.begin(), RootName.end()-1);
543 emitCheck("IsLegalAndProfitableToFold(" + RootName +
544 ".getNode(), " + ParentName + ".getNode(), N.getNode())");
549 if (NodeHasChain) {
550 if (FoundChain) {
551 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
552 "IsChainCompatible(" + ChainName + ".getNode(), " +
553 RootName + ".getNode()))");
554 OrigChains.push_back(std::make_pair(ChainName, RootName));
555 } else
556 FoundChain = true;
557 ChainName = "Chain" + ChainSuffix;
558 emitInit("SDValue " + ChainName + " = " + RootName +
559 ".getOperand(0);");
563 // Don't fold any node which reads or writes a flag and has multiple uses.
564 // FIXME: We really need to separate the concepts of flag and "glue". Those
565 // real flag results, e.g. X86CMP output, can have multiple uses.
566 // FIXME: If the optional incoming flag does not exist. Then it is ok to
567 // fold it.
568 if (!isRoot &&
569 (PatternHasProperty(N, SDNPInFlag, CGP) ||
570 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
571 PatternHasProperty(N, SDNPOutFlag, CGP))) {
572 if (!EmittedUseCheck) {
573 // Multiple uses of actual result?
574 emitCheck(RootName + ".hasOneUse()");
578 // If there are node predicates for this, emit the calls.
579 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
580 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
582 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
583 // a constant without a predicate fn that has more that one bit set, handle
584 // this as a special case. This is usually for targets that have special
585 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
586 // handling stuff). Using these instructions is often far more efficient
587 // than materializing the constant. Unfortunately, both the instcombiner
588 // and the dag combiner can often infer that bits are dead, and thus drop
589 // them from the mask in the dag. For example, it might turn 'AND X, 255'
590 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
591 // to handle this.
592 if (!N->isLeaf() &&
593 (N->getOperator()->getName() == "and" ||
594 N->getOperator()->getName() == "or") &&
595 N->getChild(1)->isLeaf() &&
596 N->getChild(1)->getPredicateFns().empty()) {
597 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
598 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
599 emitInit("SDValue " + RootName + "0" + " = " +
600 RootName + ".getOperand(" + utostr(0) + ");");
601 emitInit("SDValue " + RootName + "1" + " = " +
602 RootName + ".getOperand(" + utostr(1) + ");");
604 unsigned NTmp = TmpNo++;
605 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
606 " = dyn_cast<ConstantSDNode>(" + RootName + "1);");
607 emitCheck("Tmp" + utostr(NTmp));
608 const char *MaskPredicate = N->getOperator()->getName() == "or"
609 ? "CheckOrMask(" : "CheckAndMask(";
610 emitCheck(MaskPredicate + RootName + "0, Tmp" + utostr(NTmp) +
611 ", INT64_C(" + itostr(II->getValue()) + "))");
613 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
614 ChainSuffix + utostr(0), FoundChain);
615 return;
620 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
621 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
622 RootName + ".getOperand(" +utostr(OpNo) + ");");
624 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
625 ChainSuffix + utostr(OpNo), FoundChain);
628 // Handle cases when root is a complex pattern.
629 const ComplexPattern *CP;
630 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
631 std::string Fn = CP->getSelectFunc();
632 unsigned NumOps = CP->getNumOperands();
633 for (unsigned i = 0; i < NumOps; ++i) {
634 emitDecl("CPTmp" + RootName + "_" + utostr(i));
635 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
637 if (CP->hasProperty(SDNPHasChain)) {
638 emitDecl("CPInChain");
639 emitDecl("Chain" + ChainSuffix);
640 emitCode("SDValue CPInChain;");
641 emitCode("SDValue Chain" + ChainSuffix + ";");
644 std::string Code = Fn + "(" + RootName + ", " + RootName;
645 for (unsigned i = 0; i < NumOps; i++)
646 Code += ", CPTmp" + RootName + "_" + utostr(i);
647 if (CP->hasProperty(SDNPHasChain)) {
648 ChainName = "Chain" + ChainSuffix;
649 Code += ", CPInChain, Chain" + ChainSuffix;
651 emitCheck(Code + ")");
655 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
656 const std::string &RootName,
657 const std::string &ParentRootName,
658 const std::string &ChainSuffix, bool &FoundChain) {
659 if (!Child->isLeaf()) {
660 // If it's not a leaf, recursively match.
661 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
662 emitCheck(RootName + ".getOpcode() == " +
663 CInfo.getEnumName());
664 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
665 bool HasChain = false;
666 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
667 HasChain = true;
668 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
670 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
671 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
672 "Pattern folded multiple nodes which produce flags?");
673 FoldedFlag = std::make_pair(RootName,
674 CInfo.getNumResults() + (unsigned)HasChain);
676 } else {
677 // If this child has a name associated with it, capture it in VarMap. If
678 // we already saw this in the pattern, emit code to verify dagness.
679 if (!Child->getName().empty()) {
680 std::string &VarMapEntry = VariableMap[Child->getName()];
681 if (VarMapEntry.empty()) {
682 VarMapEntry = RootName;
683 } else {
684 // If we get here, this is a second reference to a specific name.
685 // Since we already have checked that the first reference is valid,
686 // we don't have to recursively match it, just check that it's the
687 // same as the previously named thing.
688 emitCheck(VarMapEntry + " == " + RootName);
689 Duplicates.insert(RootName);
690 return;
694 // Handle leaves of various types.
695 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
696 Record *LeafRec = DI->getDef();
697 if (LeafRec->isSubClassOf("RegisterClass") ||
698 LeafRec->isSubClassOf("PointerLikeRegClass")) {
699 // Handle register references. Nothing to do here.
700 } else if (LeafRec->isSubClassOf("Register")) {
701 // Handle register references.
702 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
703 // Handle complex pattern.
704 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
705 std::string Fn = CP->getSelectFunc();
706 unsigned NumOps = CP->getNumOperands();
707 for (unsigned i = 0; i < NumOps; ++i) {
708 emitDecl("CPTmp" + RootName + "_" + utostr(i));
709 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
711 if (CP->hasProperty(SDNPHasChain)) {
712 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
713 FoldedChains.push_back(std::make_pair("CPInChain",
714 PInfo.getNumResults()));
715 ChainName = "Chain" + ChainSuffix;
716 emitDecl("CPInChain");
717 emitDecl(ChainName);
718 emitCode("SDValue CPInChain;");
719 emitCode("SDValue " + ChainName + ";");
722 std::string Code = Fn + "(";
723 if (CP->hasAttribute(CPAttrParentAsRoot)) {
724 Code += ParentRootName + ", ";
725 } else {
726 Code += "N, ";
728 if (CP->hasProperty(SDNPHasChain)) {
729 std::string ParentName(RootName.begin(), RootName.end()-1);
730 Code += ParentName + ", ";
732 Code += RootName;
733 for (unsigned i = 0; i < NumOps; i++)
734 Code += ", CPTmp" + RootName + "_" + utostr(i);
735 if (CP->hasProperty(SDNPHasChain))
736 Code += ", CPInChain, Chain" + ChainSuffix;
737 emitCheck(Code + ")");
738 } else if (LeafRec->getName() == "srcvalue") {
739 // Place holder for SRCVALUE nodes. Nothing to do here.
740 } else if (LeafRec->isSubClassOf("ValueType")) {
741 // Make sure this is the specified value type.
742 emitCheck("cast<VTSDNode>(" + RootName +
743 ")->getVT() == MVT::" + LeafRec->getName());
744 } else if (LeafRec->isSubClassOf("CondCode")) {
745 // Make sure this is the specified cond code.
746 emitCheck("cast<CondCodeSDNode>(" + RootName +
747 ")->get() == ISD::" + LeafRec->getName());
748 } else {
749 #ifndef NDEBUG
750 Child->dump();
751 errs() << " ";
752 #endif
753 assert(0 && "Unknown leaf type!");
756 // If there are node predicates for this, emit the calls.
757 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
758 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
759 ".getNode())");
760 } else if (IntInit *II =
761 dynamic_cast<IntInit*>(Child->getLeafValue())) {
762 unsigned NTmp = TmpNo++;
763 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
764 " = dyn_cast<ConstantSDNode>("+
765 RootName + ");");
766 emitCheck("Tmp" + utostr(NTmp));
767 unsigned CTmp = TmpNo++;
768 emitCode("int64_t CN"+ utostr(CTmp) +
769 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
770 emitCheck("CN" + utostr(CTmp) + " == "
771 "INT64_C(" +itostr(II->getValue()) + ")");
772 } else {
773 #ifndef NDEBUG
774 Child->dump();
775 #endif
776 assert(0 && "Unknown leaf type!");
781 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
782 /// we actually have to build a DAG!
783 std::vector<std::string>
784 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
785 bool InFlagDecled, bool ResNodeDecled,
786 bool LikeLeaf = false, bool isRoot = false) {
787 // List of arguments of getTargetNode() or SelectNodeTo().
788 std::vector<std::string> NodeOps;
789 // This is something selected from the pattern we matched.
790 if (!N->getName().empty()) {
791 const std::string &VarName = N->getName();
792 std::string Val = VariableMap[VarName];
793 bool ModifiedVal = false;
794 if (Val.empty()) {
795 errs() << "Variable '" << VarName << " referenced but not defined "
796 << "and not caught earlier!\n";
797 abort();
799 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
800 // Already selected this operand, just return the tmpval.
801 NodeOps.push_back(Val);
802 return NodeOps;
805 const ComplexPattern *CP;
806 unsigned ResNo = TmpNo++;
807 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
808 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
809 std::string CastType;
810 std::string TmpVar = "Tmp" + utostr(ResNo);
811 switch (N->getTypeNum(0)) {
812 default:
813 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
814 << " type as an immediate constant. Aborting\n";
815 abort();
816 case MVT::i1: CastType = "bool"; break;
817 case MVT::i8: CastType = "unsigned char"; break;
818 case MVT::i16: CastType = "unsigned short"; break;
819 case MVT::i32: CastType = "unsigned"; break;
820 case MVT::i64: CastType = "uint64_t"; break;
822 emitCode("SDValue " + TmpVar +
823 " = CurDAG->getTargetConstant(((" + CastType +
824 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
825 getEnumName(N->getTypeNum(0)) + ");");
826 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
827 // value if used multiple times by this pattern result.
828 Val = TmpVar;
829 ModifiedVal = true;
830 NodeOps.push_back(Val);
831 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
832 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
833 std::string TmpVar = "Tmp" + utostr(ResNo);
834 emitCode("SDValue " + TmpVar +
835 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
836 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
837 Val + ")->getValueType(0));");
838 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
839 // value if used multiple times by this pattern result.
840 Val = TmpVar;
841 ModifiedVal = true;
842 NodeOps.push_back(Val);
843 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
844 Record *Op = OperatorMap[N->getName()];
845 // Transform ExternalSymbol to TargetExternalSymbol
846 if (Op && Op->getName() == "externalsym") {
847 std::string TmpVar = "Tmp"+utostr(ResNo);
848 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
849 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
850 Val + ")->getSymbol(), " +
851 getEnumName(N->getTypeNum(0)) + ");");
852 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
853 // this value if used multiple times by this pattern result.
854 Val = TmpVar;
855 ModifiedVal = true;
857 NodeOps.push_back(Val);
858 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
859 || N->getOperator()->getName() == "tglobaltlsaddr")) {
860 Record *Op = OperatorMap[N->getName()];
861 // Transform GlobalAddress to TargetGlobalAddress
862 if (Op && (Op->getName() == "globaladdr" ||
863 Op->getName() == "globaltlsaddr")) {
864 std::string TmpVar = "Tmp" + utostr(ResNo);
865 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
866 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
867 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
868 ");");
869 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
870 // this value if used multiple times by this pattern result.
871 Val = TmpVar;
872 ModifiedVal = true;
874 NodeOps.push_back(Val);
875 } else if (!N->isLeaf()
876 && (N->getOperator()->getName() == "texternalsym"
877 || N->getOperator()->getName() == "tconstpool")) {
878 // Do not rewrite the variable name, since we don't generate a new
879 // temporary.
880 NodeOps.push_back(Val);
881 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
882 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
883 NodeOps.push_back("CPTmp" + Val + "_" + utostr(i));
885 } else {
886 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
887 // node even if it isn't one. Don't select it.
888 if (!LikeLeaf) {
889 if (isRoot && N->isLeaf()) {
890 emitCode("ReplaceUses(N, " + Val + ");");
891 emitCode("return NULL;");
894 NodeOps.push_back(Val);
897 if (ModifiedVal) {
898 VariableMap[VarName] = Val;
900 return NodeOps;
902 if (N->isLeaf()) {
903 // If this is an explicit register reference, handle it.
904 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
905 unsigned ResNo = TmpNo++;
906 if (DI->getDef()->isSubClassOf("Register")) {
907 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
908 getQualifiedName(DI->getDef()) + ", " +
909 getEnumName(N->getTypeNum(0)) + ");");
910 NodeOps.push_back("Tmp" + utostr(ResNo));
911 return NodeOps;
912 } else if (DI->getDef()->getName() == "zero_reg") {
913 emitCode("SDValue Tmp" + utostr(ResNo) +
914 " = CurDAG->getRegister(0, " +
915 getEnumName(N->getTypeNum(0)) + ");");
916 NodeOps.push_back("Tmp" + utostr(ResNo));
917 return NodeOps;
918 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
919 // Handle a reference to a register class. This is used
920 // in COPY_TO_SUBREG instructions.
921 emitCode("SDValue Tmp" + utostr(ResNo) +
922 " = CurDAG->getTargetConstant(" +
923 getQualifiedName(DI->getDef()) + "RegClassID, " +
924 "MVT::i32);");
925 NodeOps.push_back("Tmp" + utostr(ResNo));
926 return NodeOps;
928 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
929 unsigned ResNo = TmpNo++;
930 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
931 emitCode("SDValue Tmp" + utostr(ResNo) +
932 " = CurDAG->getTargetConstant(0x" +
933 utohexstr((uint64_t) II->getValue()) +
934 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
935 NodeOps.push_back("Tmp" + utostr(ResNo));
936 return NodeOps;
939 #ifndef NDEBUG
940 N->dump();
941 #endif
942 assert(0 && "Unknown leaf type!");
943 return NodeOps;
946 Record *Op = N->getOperator();
947 if (Op->isSubClassOf("Instruction")) {
948 const CodeGenTarget &CGT = CGP.getTargetInfo();
949 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
950 const DAGInstruction &Inst = CGP.getInstruction(Op);
951 const TreePattern *InstPat = Inst.getPattern();
952 // FIXME: Assume actual pattern comes before "implicit".
953 TreePatternNode *InstPatNode =
954 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
955 : (InstPat ? InstPat->getTree(0) : NULL);
956 if (InstPatNode && !InstPatNode->isLeaf() &&
957 InstPatNode->getOperator()->getName() == "set") {
958 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
960 bool IsVariadic = isRoot && II.isVariadic;
961 // FIXME: fix how we deal with physical register operands.
962 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
963 bool HasImpResults = isRoot && DstRegs.size() > 0;
964 bool NodeHasOptInFlag = isRoot &&
965 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
966 bool NodeHasInFlag = isRoot &&
967 PatternHasProperty(Pattern, SDNPInFlag, CGP);
968 bool NodeHasOutFlag = isRoot &&
969 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
970 bool NodeHasChain = InstPatNode &&
971 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
972 bool InputHasChain = isRoot &&
973 NodeHasProperty(Pattern, SDNPHasChain, CGP);
974 unsigned NumResults = Inst.getNumResults();
975 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
977 // Record output varargs info.
978 OutputIsVariadic = IsVariadic;
980 if (NodeHasOptInFlag) {
981 emitCode("bool HasInFlag = "
982 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
984 if (IsVariadic)
985 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
987 // How many results is this pattern expected to produce?
988 unsigned NumPatResults = 0;
989 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
990 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
991 if (VT != MVT::isVoid && VT != MVT::Flag)
992 NumPatResults++;
995 if (OrigChains.size() > 0) {
996 // The original input chain is being ignored. If it is not just
997 // pointing to the op that's being folded, we should create a
998 // TokenFactor with it and the chain of the folded op as the new chain.
999 // We could potentially be doing multiple levels of folding, in that
1000 // case, the TokenFactor can have more operands.
1001 emitCode("SmallVector<SDValue, 8> InChains;");
1002 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1003 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1004 OrigChains[i].second + ".getNode()) {");
1005 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1006 emitCode("}");
1008 emitCode("InChains.push_back(" + ChainName + ");");
1009 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1010 "N.getDebugLoc(), MVT::Other, "
1011 "&InChains[0], InChains.size());");
1012 if (GenDebug) {
1013 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1014 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1018 // Loop over all of the operands of the instruction pattern, emitting code
1019 // to fill them all in. The node 'N' usually has number children equal to
1020 // the number of input operands of the instruction. However, in cases
1021 // where there are predicate operands for an instruction, we need to fill
1022 // in the 'execute always' values. Match up the node operands to the
1023 // instruction operands to do this.
1024 std::vector<std::string> AllOps;
1025 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1026 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1027 std::vector<std::string> Ops;
1029 // Determine what to emit for this operand.
1030 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1031 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1032 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1033 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1034 // This is a predicate or optional def operand; emit the
1035 // 'default ops' operands.
1036 const DAGDefaultOperand &DefaultOp =
1037 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1038 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1039 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1040 InFlagDecled, ResNodeDecled);
1041 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1043 } else {
1044 // Otherwise this is a normal operand or a predicate operand without
1045 // 'execute always'; emit it.
1046 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1047 InFlagDecled, ResNodeDecled);
1048 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1049 ++ChildNo;
1053 // Emit all the chain and CopyToReg stuff.
1054 bool ChainEmitted = NodeHasChain;
1055 if (NodeHasInFlag || HasImpInputs)
1056 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1057 InFlagDecled, ResNodeDecled, true);
1058 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1059 if (!InFlagDecled) {
1060 emitCode("SDValue InFlag(0, 0);");
1061 InFlagDecled = true;
1063 if (NodeHasOptInFlag) {
1064 emitCode("if (HasInFlag) {");
1065 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
1066 emitCode("}");
1070 unsigned ResNo = TmpNo++;
1072 unsigned OpsNo = OpcNo;
1073 std::string CodePrefix;
1074 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1075 std::deque<std::string> After;
1076 std::string NodeName;
1077 if (!isRoot) {
1078 NodeName = "Tmp" + utostr(ResNo);
1079 CodePrefix = "SDValue " + NodeName + "(";
1080 } else {
1081 NodeName = "ResNode";
1082 if (!ResNodeDecled) {
1083 CodePrefix = "SDNode *" + NodeName + " = ";
1084 ResNodeDecled = true;
1085 } else
1086 CodePrefix = NodeName + " = ";
1089 std::string Code = "Opc" + utostr(OpcNo);
1091 if (!isRoot || (InputHasChain && !NodeHasChain))
1092 // For call to "getTargetNode()".
1093 Code += ", N.getDebugLoc()";
1095 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1097 // Output order: results, chain, flags
1098 // Result types.
1099 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1100 Code += ", VT" + utostr(VTNo);
1101 emitVT(getEnumName(N->getTypeNum(0)));
1103 // Add types for implicit results in physical registers, scheduler will
1104 // care of adding copyfromreg nodes.
1105 for (unsigned i = 0; i < NumDstRegs; i++) {
1106 Record *RR = DstRegs[i];
1107 if (RR->isSubClassOf("Register")) {
1108 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1109 Code += ", " + getEnumName(RVT);
1112 if (NodeHasChain)
1113 Code += ", MVT::Other";
1114 if (NodeHasOutFlag)
1115 Code += ", MVT::Flag";
1117 // Inputs.
1118 if (IsVariadic) {
1119 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1120 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1121 AllOps.clear();
1123 // Figure out whether any operands at the end of the op list are not
1124 // part of the variable section.
1125 std::string EndAdjust;
1126 if (NodeHasInFlag || HasImpInputs)
1127 EndAdjust = "-1"; // Always has one flag.
1128 else if (NodeHasOptInFlag)
1129 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1131 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1132 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1134 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1135 emitCode("}");
1138 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1139 // this pattern.
1140 if (II.mayLoad | II.mayStore) {
1141 std::vector<std::string>::const_iterator mi, mie;
1142 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
1143 std::string LSIName = "LSI_" + *mi;
1144 emitCode("SDValue " + LSIName + " = "
1145 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1146 *mi + ")->getMemOperand());");
1147 if (GenDebug) {
1148 emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"yellow\");");
1149 emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"black\");");
1151 if (IsVariadic)
1152 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + LSIName + ");");
1153 else
1154 AllOps.push_back(LSIName);
1158 if (NodeHasChain) {
1159 if (IsVariadic)
1160 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1161 else
1162 AllOps.push_back(ChainName);
1165 if (IsVariadic) {
1166 if (NodeHasInFlag || HasImpInputs)
1167 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1168 else if (NodeHasOptInFlag) {
1169 emitCode("if (HasInFlag)");
1170 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1172 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1173 ".size()";
1174 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1175 AllOps.push_back("InFlag");
1177 unsigned NumOps = AllOps.size();
1178 if (NumOps) {
1179 if (!NodeHasOptInFlag && NumOps < 4) {
1180 for (unsigned i = 0; i != NumOps; ++i)
1181 Code += ", " + AllOps[i];
1182 } else {
1183 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1184 for (unsigned i = 0; i != NumOps; ++i) {
1185 OpsCode += AllOps[i];
1186 if (i != NumOps-1)
1187 OpsCode += ", ";
1189 emitCode(OpsCode + " };");
1190 Code += ", Ops" + utostr(OpsNo) + ", ";
1191 if (NodeHasOptInFlag) {
1192 Code += "HasInFlag ? ";
1193 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1194 } else
1195 Code += utostr(NumOps);
1199 if (!isRoot)
1200 Code += "), 0";
1202 std::vector<std::string> ReplaceFroms;
1203 std::vector<std::string> ReplaceTos;
1204 if (!isRoot) {
1205 NodeOps.push_back("Tmp" + utostr(ResNo));
1206 } else {
1208 if (NodeHasOutFlag) {
1209 if (!InFlagDecled) {
1210 After.push_back("SDValue InFlag(ResNode, " +
1211 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1212 ");");
1213 InFlagDecled = true;
1214 } else
1215 After.push_back("InFlag = SDValue(ResNode, " +
1216 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1217 ");");
1220 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1221 ReplaceFroms.push_back("SDValue(" +
1222 FoldedChains[j].first + ".getNode(), " +
1223 utostr(FoldedChains[j].second) +
1224 ")");
1225 ReplaceTos.push_back("SDValue(ResNode, " +
1226 utostr(NumResults+NumDstRegs) + ")");
1229 if (NodeHasOutFlag) {
1230 if (FoldedFlag.first != "") {
1231 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1232 utostr(FoldedFlag.second) + ")");
1233 ReplaceTos.push_back("InFlag");
1234 } else {
1235 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1236 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1237 utostr(NumPatResults + (unsigned)InputHasChain)
1238 + ")");
1239 ReplaceTos.push_back("InFlag");
1243 if (!ReplaceFroms.empty() && InputHasChain) {
1244 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1245 utostr(NumPatResults) + ")");
1246 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1247 ChainName + ".getResNo()" + ")");
1248 ChainAssignmentNeeded |= NodeHasChain;
1251 // User does not expect the instruction would produce a chain!
1252 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1254 } else if (InputHasChain && !NodeHasChain) {
1255 // One of the inner node produces a chain.
1256 if (NodeHasOutFlag) {
1257 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1258 utostr(NumPatResults+1) +
1259 ")");
1260 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
1262 ReplaceFroms.push_back("SDValue(N.getNode(), " +
1263 utostr(NumPatResults) + ")");
1264 ReplaceTos.push_back(ChainName);
1268 if (ChainAssignmentNeeded) {
1269 // Remember which op produces the chain.
1270 std::string ChainAssign;
1271 if (!isRoot)
1272 ChainAssign = ChainName + " = SDValue(" + NodeName +
1273 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1274 else
1275 ChainAssign = ChainName + " = SDValue(" + NodeName +
1276 ", " + utostr(NumResults+NumDstRegs) + ");";
1278 After.push_front(ChainAssign);
1281 if (ReplaceFroms.size() == 1) {
1282 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1283 ReplaceTos[0] + ");");
1284 } else if (!ReplaceFroms.empty()) {
1285 After.push_back("const SDValue Froms[] = {");
1286 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1287 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1288 After.push_back("};");
1289 After.push_back("const SDValue Tos[] = {");
1290 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1291 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1292 After.push_back("};");
1293 After.push_back("ReplaceUses(Froms, Tos, " +
1294 itostr(ReplaceFroms.size()) + ");");
1297 // We prefer to use SelectNodeTo since it avoids allocation when
1298 // possible and it avoids CSE map recalculation for the node's
1299 // users, however it's tricky to use in a non-root context.
1301 // We also don't use if the pattern replacement is being used to
1302 // jettison a chain result, since morphing the node in place
1303 // would leave users of the chain dangling.
1305 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1306 Code = "CurDAG->getTargetNode(" + Code;
1307 } else {
1308 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
1310 if (isRoot) {
1311 if (After.empty())
1312 CodePrefix = "return ";
1313 else
1314 After.push_back("return ResNode;");
1317 emitCode(CodePrefix + Code + ");");
1319 if (GenDebug) {
1320 if (!isRoot) {
1321 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1322 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1324 else {
1325 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1326 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1330 for (unsigned i = 0, e = After.size(); i != e; ++i)
1331 emitCode(After[i]);
1333 return NodeOps;
1335 if (Op->isSubClassOf("SDNodeXForm")) {
1336 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1337 // PatLeaf node - the operand may or may not be a leaf node. But it should
1338 // behave like one.
1339 std::vector<std::string> Ops =
1340 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1341 ResNodeDecled, true);
1342 unsigned ResNo = TmpNo++;
1343 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1344 + "(" + Ops.back() + ".getNode());");
1345 NodeOps.push_back("Tmp" + utostr(ResNo));
1346 if (isRoot)
1347 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1348 return NodeOps;
1351 N->dump();
1352 errs() << "\n";
1353 throw std::string("Unknown node in result pattern!");
1356 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1357 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1358 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1359 /// for, this returns true otherwise false if Pat has all types.
1360 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1361 const std::string &Prefix, bool isRoot = false) {
1362 // Did we find one?
1363 if (Pat->getExtTypes() != Other->getExtTypes()) {
1364 // Move a type over from 'other' to 'pat'.
1365 Pat->setTypes(Other->getExtTypes());
1366 // The top level node type is checked outside of the select function.
1367 if (!isRoot)
1368 emitCheck(Prefix + ".getNode()->getValueType(0) == " +
1369 getName(Pat->getTypeNum(0)));
1370 return true;
1373 unsigned OpNo =
1374 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
1375 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1376 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1377 Prefix + utostr(OpNo)))
1378 return true;
1379 return false;
1382 private:
1383 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1384 /// being built.
1385 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1386 bool &ChainEmitted, bool &InFlagDecled,
1387 bool &ResNodeDecled, bool isRoot = false) {
1388 const CodeGenTarget &T = CGP.getTargetInfo();
1389 unsigned OpNo =
1390 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1391 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
1392 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1393 TreePatternNode *Child = N->getChild(i);
1394 if (!Child->isLeaf()) {
1395 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1396 InFlagDecled, ResNodeDecled);
1397 } else {
1398 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1399 if (!Child->getName().empty()) {
1400 std::string Name = RootName + utostr(OpNo);
1401 if (Duplicates.find(Name) != Duplicates.end())
1402 // A duplicate! Do not emit a copy for this node.
1403 continue;
1406 Record *RR = DI->getDef();
1407 if (RR->isSubClassOf("Register")) {
1408 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
1409 if (RVT == MVT::Flag) {
1410 if (!InFlagDecled) {
1411 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
1412 InFlagDecled = true;
1413 } else
1414 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1415 } else {
1416 if (!ChainEmitted) {
1417 emitCode("SDValue Chain = CurDAG->getEntryNode();");
1418 ChainName = "Chain";
1419 ChainEmitted = true;
1421 if (!InFlagDecled) {
1422 emitCode("SDValue InFlag(0, 0);");
1423 InFlagDecled = true;
1425 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1426 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
1427 ", " + RootName + ".getDebugLoc()" +
1428 ", " + getQualifiedName(RR) +
1429 ", " + RootName + utostr(OpNo) + ", InFlag).getNode();");
1430 ResNodeDecled = true;
1431 emitCode(ChainName + " = SDValue(ResNode, 0);");
1432 emitCode("InFlag = SDValue(ResNode, 1);");
1439 if (HasInFlag) {
1440 if (!InFlagDecled) {
1441 emitCode("SDValue InFlag = " + RootName +
1442 ".getOperand(" + utostr(OpNo) + ");");
1443 InFlagDecled = true;
1444 } else
1445 emitCode("InFlag = " + RootName +
1446 ".getOperand(" + utostr(OpNo) + ");");
1451 /// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1452 /// stream to match the pattern, and generate the code for the match if it
1453 /// succeeds. Returns true if the pattern is not guaranteed to match.
1454 void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
1455 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1456 std::set<std::string> &GeneratedDecl,
1457 std::vector<std::string> &TargetOpcodes,
1458 std::vector<std::string> &TargetVTs,
1459 bool &OutputIsVariadic,
1460 unsigned &NumInputRootOps) {
1461 OutputIsVariadic = false;
1462 NumInputRootOps = 0;
1464 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
1465 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1466 GeneratedCode, GeneratedDecl,
1467 TargetOpcodes, TargetVTs,
1468 OutputIsVariadic, NumInputRootOps);
1470 // Emit the matcher, capturing named arguments in VariableMap.
1471 bool FoundChain = false;
1472 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1474 // TP - Get *SOME* tree pattern, we don't care which.
1475 TreePattern &TP = *CGP.pf_begin()->second;
1477 // At this point, we know that we structurally match the pattern, but the
1478 // types of the nodes may not match. Figure out the fewest number of type
1479 // comparisons we need to emit. For example, if there is only one integer
1480 // type supported by a target, there should be no type comparisons at all for
1481 // integer patterns!
1483 // To figure out the fewest number of type checks needed, clone the pattern,
1484 // remove the types, then perform type inference on the pattern as a whole.
1485 // If there are unresolved types, emit an explicit check for those types,
1486 // apply the type to the tree, then rerun type inference. Iterate until all
1487 // types are resolved.
1489 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1490 RemoveAllTypes(Pat);
1492 do {
1493 // Resolve/propagate as many types as possible.
1494 try {
1495 bool MadeChange = true;
1496 while (MadeChange)
1497 MadeChange = Pat->ApplyTypeConstraints(TP,
1498 true/*Ignore reg constraints*/);
1499 } catch (...) {
1500 assert(0 && "Error: could not find consistent types for something we"
1501 " already decided was ok!");
1502 abort();
1505 // Insert a check for an unresolved type and add it to the tree. If we find
1506 // an unresolved type to add a check for, this returns true and we iterate,
1507 // otherwise we are done.
1508 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1510 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
1511 false, false, false, true);
1512 delete Pat;
1515 /// EraseCodeLine - Erase one code line from all of the patterns. If removing
1516 /// a line causes any of them to be empty, remove them and return true when
1517 /// done.
1518 static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
1519 std::vector<std::pair<unsigned, std::string> > > >
1520 &Patterns) {
1521 bool ErasedPatterns = false;
1522 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1523 Patterns[i].second.pop_back();
1524 if (Patterns[i].second.empty()) {
1525 Patterns.erase(Patterns.begin()+i);
1526 --i; --e;
1527 ErasedPatterns = true;
1530 return ErasedPatterns;
1533 /// EmitPatterns - Emit code for at least one pattern, but try to group common
1534 /// code together between the patterns.
1535 void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
1536 std::vector<std::pair<unsigned, std::string> > > >
1537 &Patterns, unsigned Indent,
1538 raw_ostream &OS) {
1539 typedef std::pair<unsigned, std::string> CodeLine;
1540 typedef std::vector<CodeLine> CodeList;
1541 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
1543 if (Patterns.empty()) return;
1545 // Figure out how many patterns share the next code line. Explicitly copy
1546 // FirstCodeLine so that we don't invalidate a reference when changing
1547 // Patterns.
1548 const CodeLine FirstCodeLine = Patterns.back().second.back();
1549 unsigned LastMatch = Patterns.size()-1;
1550 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1551 --LastMatch;
1553 // If not all patterns share this line, split the list into two pieces. The
1554 // first chunk will use this line, the second chunk won't.
1555 if (LastMatch != 0) {
1556 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1557 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1559 // FIXME: Emit braces?
1560 if (Shared.size() == 1) {
1561 const PatternToMatch &Pattern = *Shared.back().first;
1562 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1563 Pattern.getSrcPattern()->print(OS);
1564 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1565 Pattern.getDstPattern()->print(OS);
1566 OS << "\n";
1567 unsigned AddedComplexity = Pattern.getAddedComplexity();
1568 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1569 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1570 << " cost = "
1571 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1572 << " size = "
1573 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1575 if (FirstCodeLine.first != 1) {
1576 OS << std::string(Indent, ' ') << "{\n";
1577 Indent += 2;
1579 EmitPatterns(Shared, Indent, OS);
1580 if (FirstCodeLine.first != 1) {
1581 Indent -= 2;
1582 OS << std::string(Indent, ' ') << "}\n";
1585 if (Other.size() == 1) {
1586 const PatternToMatch &Pattern = *Other.back().first;
1587 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1588 Pattern.getSrcPattern()->print(OS);
1589 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1590 Pattern.getDstPattern()->print(OS);
1591 OS << "\n";
1592 unsigned AddedComplexity = Pattern.getAddedComplexity();
1593 OS << std::string(Indent, ' ') << "// Pattern complexity = "
1594 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
1595 << " cost = "
1596 << getResultPatternCost(Pattern.getDstPattern(), CGP)
1597 << " size = "
1598 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
1600 EmitPatterns(Other, Indent, OS);
1601 return;
1604 // Remove this code from all of the patterns that share it.
1605 bool ErasedPatterns = EraseCodeLine(Patterns);
1607 bool isPredicate = FirstCodeLine.first == 1;
1609 // Otherwise, every pattern in the list has this line. Emit it.
1610 if (!isPredicate) {
1611 // Normal code.
1612 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1613 } else {
1614 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1616 // If the next code line is another predicate, and if all of the pattern
1617 // in this group share the same next line, emit it inline now. Do this
1618 // until we run out of common predicates.
1619 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1620 // Check that all of the patterns in Patterns end with the same predicate.
1621 bool AllEndWithSamePredicate = true;
1622 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1623 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1624 AllEndWithSamePredicate = false;
1625 break;
1627 // If all of the predicates aren't the same, we can't share them.
1628 if (!AllEndWithSamePredicate) break;
1630 // Otherwise we can. Emit it shared now.
1631 OS << " &&\n" << std::string(Indent+4, ' ')
1632 << Patterns.back().second.back().second;
1633 ErasedPatterns = EraseCodeLine(Patterns);
1636 OS << ") {\n";
1637 Indent += 2;
1640 EmitPatterns(Patterns, Indent, OS);
1642 if (isPredicate)
1643 OS << std::string(Indent-2, ' ') << "}\n";
1646 static std::string getLegalCName(std::string OpName) {
1647 std::string::size_type pos = OpName.find("::");
1648 if (pos != std::string::npos)
1649 OpName.replace(pos, 2, "_");
1650 return OpName;
1653 void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
1654 const CodeGenTarget &Target = CGP.getTargetInfo();
1656 // Get the namespace to insert instructions into.
1657 std::string InstNS = Target.getInstNamespace();
1658 if (!InstNS.empty()) InstNS += "::";
1660 // Group the patterns by their top-level opcodes.
1661 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
1662 // All unique target node emission functions.
1663 std::map<std::string, unsigned> EmitFunctions;
1664 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1665 E = CGP.ptm_end(); I != E; ++I) {
1666 const PatternToMatch &Pattern = *I;
1668 TreePatternNode *Node = Pattern.getSrcPattern();
1669 if (!Node->isLeaf()) {
1670 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
1671 push_back(&Pattern);
1672 } else {
1673 const ComplexPattern *CP;
1674 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
1675 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
1676 push_back(&Pattern);
1677 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
1678 std::vector<Record*> OpNodes = CP->getRootNodes();
1679 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
1680 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1681 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
1682 &Pattern);
1684 } else {
1685 errs() << "Unrecognized opcode '";
1686 Node->dump();
1687 errs() << "' on tree pattern '";
1688 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
1689 exit(1);
1694 // For each opcode, there might be multiple select functions, one per
1695 // ValueType of the node (or its first operand if it doesn't produce a
1696 // non-chain result.
1697 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1699 // Emit one Select_* method for each top-level opcode. We do this instead of
1700 // emitting one giant switch statement to support compilers where this will
1701 // result in the recursive functions taking less stack space.
1702 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1703 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1704 PBOI != E; ++PBOI) {
1705 const std::string &OpName = PBOI->first;
1706 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
1707 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1709 // Split them into groups by type.
1710 std::map<MVT::SimpleValueType,
1711 std::vector<const PatternToMatch*> > PatternsByType;
1712 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
1713 const PatternToMatch *Pat = PatternsOfOp[i];
1714 TreePatternNode *SrcPat = Pat->getSrcPattern();
1715 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
1718 for (std::map<MVT::SimpleValueType,
1719 std::vector<const PatternToMatch*> >::iterator
1720 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1721 ++II) {
1722 MVT::SimpleValueType OpVT = II->first;
1723 std::vector<const PatternToMatch*> &Patterns = II->second;
1724 typedef std::pair<unsigned, std::string> CodeLine;
1725 typedef std::vector<CodeLine> CodeList;
1726 typedef CodeList::iterator CodeListI;
1728 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
1729 std::vector<std::vector<std::string> > PatternOpcodes;
1730 std::vector<std::vector<std::string> > PatternVTs;
1731 std::vector<std::set<std::string> > PatternDecls;
1732 std::vector<bool> OutputIsVariadicFlags;
1733 std::vector<unsigned> NumInputRootOpsCounts;
1734 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1735 CodeList GeneratedCode;
1736 std::set<std::string> GeneratedDecl;
1737 std::vector<std::string> TargetOpcodes;
1738 std::vector<std::string> TargetVTs;
1739 bool OutputIsVariadic;
1740 unsigned NumInputRootOps;
1741 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1742 TargetOpcodes, TargetVTs,
1743 OutputIsVariadic, NumInputRootOps);
1744 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1745 PatternDecls.push_back(GeneratedDecl);
1746 PatternOpcodes.push_back(TargetOpcodes);
1747 PatternVTs.push_back(TargetVTs);
1748 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1749 NumInputRootOpsCounts.push_back(NumInputRootOps);
1752 // Factor target node emission code (emitted by EmitResultCode) into
1753 // separate functions. Uniquing and share them among all instruction
1754 // selection routines.
1755 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1756 CodeList &GeneratedCode = CodeForPatterns[i].second;
1757 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1758 std::vector<std::string> &TargetVTs = PatternVTs[i];
1759 std::set<std::string> Decls = PatternDecls[i];
1760 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1761 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
1762 std::vector<std::string> AddedInits;
1763 int CodeSize = (int)GeneratedCode.size();
1764 int LastPred = -1;
1765 for (int j = CodeSize-1; j >= 0; --j) {
1766 if (LastPred == -1 && GeneratedCode[j].first == 1)
1767 LastPred = j;
1768 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1769 AddedInits.push_back(GeneratedCode[j].second);
1772 std::string CalleeCode = "(const SDValue &N";
1773 std::string CallerCode = "(N";
1774 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1775 CalleeCode += ", unsigned Opc" + utostr(j);
1776 CallerCode += ", " + TargetOpcodes[j];
1778 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1779 CalleeCode += ", EVT VT" + utostr(j);
1780 CallerCode += ", " + TargetVTs[j];
1782 for (std::set<std::string>::iterator
1783 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1784 std::string Name = *I;
1785 CalleeCode += ", SDValue &" + Name;
1786 CallerCode += ", " + Name;
1789 if (OutputIsVariadic) {
1790 CalleeCode += ", unsigned NumInputRootOps";
1791 CallerCode += ", " + utostr(NumInputRootOps);
1794 CallerCode += ");";
1795 CalleeCode += ") ";
1796 // Prevent emission routines from being inlined to reduce selection
1797 // routines stack frame sizes.
1798 CalleeCode += "DISABLE_INLINE ";
1799 CalleeCode += "{\n";
1801 for (std::vector<std::string>::const_reverse_iterator
1802 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1803 CalleeCode += " " + *I + "\n";
1805 for (int j = LastPred+1; j < CodeSize; ++j)
1806 CalleeCode += " " + GeneratedCode[j].second + "\n";
1807 for (int j = LastPred+1; j < CodeSize; ++j)
1808 GeneratedCode.pop_back();
1809 CalleeCode += "}\n";
1811 // Uniquing the emission routines.
1812 unsigned EmitFuncNum;
1813 std::map<std::string, unsigned>::iterator EFI =
1814 EmitFunctions.find(CalleeCode);
1815 if (EFI != EmitFunctions.end()) {
1816 EmitFuncNum = EFI->second;
1817 } else {
1818 EmitFuncNum = EmitFunctions.size();
1819 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1820 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1823 // Replace the emission code within selection routines with calls to the
1824 // emission functions.
1825 if (GenDebug) {
1826 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1828 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1829 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1830 if (GenDebug) {
1831 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1832 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1833 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1834 GeneratedCode.push_back(std::make_pair(0, "}"));
1835 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1837 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
1840 // Print function.
1841 std::string OpVTStr;
1842 if (OpVT == MVT::iPTR) {
1843 OpVTStr = "_iPTR";
1844 } else if (OpVT == MVT::iPTRAny) {
1845 OpVTStr = "_iPTRAny";
1846 } else if (OpVT == MVT::isVoid) {
1847 // Nodes with a void result actually have a first result type of either
1848 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1849 // void to this case, we handle it specially here.
1850 } else {
1851 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1853 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1854 OpcodeVTMap.find(OpName);
1855 if (OpVTI == OpcodeVTMap.end()) {
1856 std::vector<std::string> VTSet;
1857 VTSet.push_back(OpVTStr);
1858 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1859 } else
1860 OpVTI->second.push_back(OpVTStr);
1862 // We want to emit all of the matching code now. However, we want to emit
1863 // the matches in order of minimal cost. Sort the patterns so the least
1864 // cost one is at the start.
1865 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1866 PatternSortingPredicate(CGP));
1868 // Scan the code to see if all of the patterns are reachable and if it is
1869 // possible that the last one might not match.
1870 bool mightNotMatch = true;
1871 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1872 CodeList &GeneratedCode = CodeForPatterns[i].second;
1873 mightNotMatch = false;
1875 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1876 if (GeneratedCode[j].first == 1) { // predicate.
1877 mightNotMatch = true;
1878 break;
1882 // If this pattern definitely matches, and if it isn't the last one, the
1883 // patterns after it CANNOT ever match. Error out.
1884 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1885 errs() << "Pattern '";
1886 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1887 errs() << "' is impossible to select!\n";
1888 exit(1);
1892 // Loop through and reverse all of the CodeList vectors, as we will be
1893 // accessing them from their logical front, but accessing the end of a
1894 // vector is more efficient.
1895 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1896 CodeList &GeneratedCode = CodeForPatterns[i].second;
1897 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1900 // Next, reverse the list of patterns itself for the same reason.
1901 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1903 OS << "SDNode *Select_" << getLegalCName(OpName)
1904 << OpVTStr << "(const SDValue &N) {\n";
1906 // Emit all of the patterns now, grouped together to share code.
1907 EmitPatterns(CodeForPatterns, 2, OS);
1909 // If the last pattern has predicates (which could fail) emit code to
1910 // catch the case where nothing handles a pattern.
1911 if (mightNotMatch) {
1912 OS << "\n";
1913 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1914 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1915 OpName != "ISD::INTRINSIC_VOID")
1916 OS << " CannotYetSelect(N);\n";
1917 else
1918 OS << " CannotYetSelectIntrinsic(N);\n";
1920 OS << " return NULL;\n";
1922 OS << "}\n\n";
1926 // Emit boilerplate.
1927 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
1928 << " std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());\n"
1929 << " SelectInlineAsmMemoryOperands(Ops);\n\n"
1931 << " std::vector<EVT> VTs;\n"
1932 << " VTs.push_back(MVT::Other);\n"
1933 << " VTs.push_back(MVT::Flag);\n"
1934 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, N.getDebugLoc(), "
1935 "VTs, &Ops[0], Ops.size());\n"
1936 << " return New.getNode();\n"
1937 << "}\n\n";
1939 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
1940 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,\n"
1941 << " N.getValueType());\n"
1942 << "}\n\n";
1944 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1945 << " SDValue Chain = N.getOperand(0);\n"
1946 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1947 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1948 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,\n"
1949 << " MVT::Other, Tmp, Chain);\n"
1950 << "}\n\n";
1952 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1953 << " SDValue Chain = N.getOperand(0);\n"
1954 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
1955 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1956 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,\n"
1957 << " MVT::Other, Tmp, Chain);\n"
1958 << "}\n\n";
1960 OS << "// The main instruction selector code.\n"
1961 << "SDNode *SelectCode(SDValue N) {\n"
1962 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT().SimpleTy;\n"
1963 << " switch (N.getOpcode()) {\n"
1964 << " default:\n"
1965 << " assert(!N.isMachineOpcode() && \"Node already selected!\");\n"
1966 << " break;\n"
1967 << " case ISD::EntryToken: // These nodes remain the same.\n"
1968 << " case ISD::MEMOPERAND:\n"
1969 << " case ISD::BasicBlock:\n"
1970 << " case ISD::Register:\n"
1971 << " case ISD::HANDLENODE:\n"
1972 << " case ISD::TargetConstant:\n"
1973 << " case ISD::TargetConstantFP:\n"
1974 << " case ISD::TargetConstantPool:\n"
1975 << " case ISD::TargetFrameIndex:\n"
1976 << " case ISD::TargetExternalSymbol:\n"
1977 << " case ISD::TargetJumpTable:\n"
1978 << " case ISD::TargetGlobalTLSAddress:\n"
1979 << " case ISD::TargetGlobalAddress:\n"
1980 << " case ISD::TokenFactor:\n"
1981 << " case ISD::CopyFromReg:\n"
1982 << " case ISD::CopyToReg: {\n"
1983 << " return NULL;\n"
1984 << " }\n"
1985 << " case ISD::AssertSext:\n"
1986 << " case ISD::AssertZext: {\n"
1987 << " ReplaceUses(N, N.getOperand(0));\n"
1988 << " return NULL;\n"
1989 << " }\n"
1990 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
1991 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1992 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
1993 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
1995 // Loop over all of the case statements, emiting a call to each method we
1996 // emitted above.
1997 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
1998 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1999 PBOI != E; ++PBOI) {
2000 const std::string &OpName = PBOI->first;
2001 // Potentially multiple versions of select for this opcode. One for each
2002 // ValueType of the node (or its first true operand if it doesn't produce a
2003 // result.
2004 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2005 OpcodeVTMap.find(OpName);
2006 std::vector<std::string> &OpVTs = OpVTI->second;
2007 OS << " case " << OpName << ": {\n";
2008 // If we have only one variant and it's the default, elide the
2009 // switch. Marginally faster, and makes MSVC happier.
2010 if (OpVTs.size()==1 && OpVTs[0].empty()) {
2011 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2012 OS << " break;\n";
2013 OS << " }\n";
2014 continue;
2016 // Keep track of whether we see a pattern that has an iPtr result.
2017 bool HasPtrPattern = false;
2018 bool HasDefaultPattern = false;
2020 OS << " switch (NVT) {\n";
2021 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2022 std::string &VTStr = OpVTs[i];
2023 if (VTStr.empty()) {
2024 HasDefaultPattern = true;
2025 continue;
2028 // If this is a match on iPTR: don't emit it directly, we need special
2029 // code.
2030 if (VTStr == "_iPTR") {
2031 HasPtrPattern = true;
2032 continue;
2034 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2035 << " return Select_" << getLegalCName(OpName)
2036 << VTStr << "(N);\n";
2038 OS << " default:\n";
2040 // If there is an iPTR result version of this pattern, emit it here.
2041 if (HasPtrPattern) {
2042 OS << " if (TLI.getPointerTy() == NVT)\n";
2043 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2045 if (HasDefaultPattern) {
2046 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2048 OS << " break;\n";
2049 OS << " }\n";
2050 OS << " break;\n";
2051 OS << " }\n";
2054 OS << " } // end of big switch.\n\n"
2055 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2056 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2057 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
2058 << " CannotYetSelect(N);\n"
2059 << " } else {\n"
2060 << " CannotYetSelectIntrinsic(N);\n"
2061 << " }\n"
2062 << " return NULL;\n"
2063 << "}\n\n";
2065 OS << "void CannotYetSelect(SDValue N) DISABLE_INLINE {\n"
2066 << " std::string msg;\n"
2067 << " raw_string_ostream Msg(msg);\n"
2068 << " Msg << \"Cannot yet select: \";\n"
2069 << " N.getNode()->print(Msg, CurDAG);\n"
2070 << " llvm_report_error(Msg.str());\n"
2071 << "}\n\n";
2073 OS << "void CannotYetSelectIntrinsic(SDValue N) DISABLE_INLINE {\n"
2074 << " errs() << \"Cannot yet select: \";\n"
2075 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2076 << "N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();\n"
2077 << " llvm_report_error(\"Cannot yet select: intrinsic %\" +\n"
2078 << "Intrinsic::getName((Intrinsic::ID)iid));\n"
2079 << "}\n\n";
2082 void DAGISelEmitter::run(raw_ostream &OS) {
2083 EmitSourceFileHeader("DAG Instruction Selector for the " +
2084 CGP.getTargetInfo().getName() + " target", OS);
2086 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2087 << "// *** instruction selector class. These functions are really "
2088 << "methods.\n\n";
2090 OS << "// Include standard, target-independent definitions and methods used\n"
2091 << "// by the instruction selector.\n";
2092 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
2094 EmitNodeTransforms(OS);
2095 EmitPredicateFunctions(OS);
2097 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
2098 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
2099 I != E; ++I) {
2100 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2101 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2102 DEBUG(errs() << "\n");
2105 // At this point, we have full information about the 'Patterns' we need to
2106 // parse, both implicitly from instructions as well as from explicit pattern
2107 // definitions. Emit the resultant instruction selector.
2108 EmitInstructionSelector(OS);