blob: 55a9d36588cc317bf6026e8539753564f98547bb [file] [log] [blame]
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner30609102007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
Chris Lattnerda272d12010-02-15 08:04:42 +000015#include "DAGISelMatcher.h"
Chris Lattner54cb8fd2005-09-07 23:44:43 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000018#include "llvm/Support/CommandLine.h"
Chris Lattner54cb8fd2005-09-07 23:44:43 +000019#include "llvm/Support/Debug.h"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000020#include "llvm/Support/MathExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000021#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000022#include <algorithm>
Dan Gohman95d11092008-07-07 21:00:17 +000023#include <deque>
Daniel Dunbar1a551802009-07-03 00:10:29 +000024#include <iostream>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000025using namespace llvm;
26
Chris Lattner3d4ad292009-08-07 22:27:19 +000027static cl::opt<bool>
28GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
David Greene8ad4c002008-10-27 21:56:29 +000029
Chris Lattnerca559d02005-09-08 21:03:01 +000030//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +000031// DAGISelEmitter Helper methods
Chris Lattner54cb8fd2005-09-07 23:44:43 +000032//
33
Dan Gohmaneeb3a002010-01-05 01:24:18 +000034/// getNodeName - The top level Select_* functions have an "SDNode* N"
35/// argument. When expanding the pattern-matching code, the intermediate
36/// variables have type SDValue. This function provides a uniform way to
37/// reference the underlying "SDNode *" for both cases.
38static std::string getNodeName(const std::string &S) {
39 if (S == "N") return S;
40 return S + ".getNode()";
41}
42
43/// getNodeValue - Similar to getNodeName, except it provides a uniform
44/// way to access the SDValue for both cases.
45static std::string getValueName(const std::string &S) {
46 if (S == "N") return "SDValue(N, 0)";
47 return S;
48}
49
Chris Lattner05814af2005-09-28 17:57:56 +000050/// 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
52/// pattern.
Chris Lattnerfe718932008-01-06 01:10:31 +000053static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Owen Andersone50ed302009-08-10 22:56:29 +000054 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +000056 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR ||
59 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +000060 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +000061 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +000062 // If the root node is a ConstantSDNode, increases its size.
63 // e.g. (set R32:$dst, 0).
64 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000065 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +000066
67 // FIXME: This is a hack to statically increase the priority of patterns
68 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
69 // Later we can allow complexity / cost for each pattern to be (optionally)
70 // specified. To get best possible pattern match we'll need to dynamically
71 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner47661322010-02-14 22:22:58 +000072 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000073 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +000074 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +000075
76 // If this node has some predicate function that must match, it adds to the
77 // complexity of this node.
Dan Gohman0540e172008-10-15 06:17:21 +000078 if (!P->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +000079 ++Size;
80
Chris Lattner05814af2005-09-28 17:57:56 +000081 // Count children in the count if they are also nodes.
82 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
83 TreePatternNode *Child = P->getChild(i);
Owen Anderson825b72b2009-08-11 20:47:22 +000084 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner6cefb772008-01-05 22:25:12 +000085 Size += getPatternSize(Child, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000086 else if (Child->isLeaf()) {
87 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000088 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Chris Lattner05446e72010-02-16 23:13:59 +000089 else if (Child->getComplexPatternInfo(CGP))
Chris Lattner6cefb772008-01-05 22:25:12 +000090 Size += getPatternSize(Child, CGP);
Dan Gohman0540e172008-10-15 06:17:21 +000091 else if (!Child->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +000092 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +000093 }
Chris Lattner05814af2005-09-28 17:57:56 +000094 }
95
96 return Size;
97}
98
99/// getResultPatternCost - Compute the number of instructions for this pattern.
100/// This is a temporary hack. We should really include the instruction
101/// latencies in this calculation.
Chris Lattner6cefb772008-01-05 22:25:12 +0000102static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000103 CodeGenDAGPatterns &CGP) {
Chris Lattner05814af2005-09-28 17:57:56 +0000104 if (P->isLeaf()) return 0;
105
Evan Chengfbad7082006-02-18 02:33:09 +0000106 unsigned Cost = 0;
107 Record *Op = P->getOperator();
108 if (Op->isSubClassOf("Instruction")) {
109 Cost++;
Chris Lattner6cefb772008-01-05 22:25:12 +0000110 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohman533297b2009-10-29 18:10:34 +0000111 if (II.usesCustomInserter)
Evan Chengfbad7082006-02-18 02:33:09 +0000112 Cost += 10;
113 }
Chris Lattner05814af2005-09-28 17:57:56 +0000114 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000115 Cost += getResultPatternCost(P->getChild(i), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000116 return Cost;
117}
118
Evan Chenge6f32032006-07-19 00:24:41 +0000119/// getResultPatternCodeSize - Compute the code size of instructions for this
120/// pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000121static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000122 CodeGenDAGPatterns &CGP) {
Evan Chenge6f32032006-07-19 00:24:41 +0000123 if (P->isLeaf()) return 0;
124
125 unsigned Cost = 0;
126 Record *Op = P->getOperator();
127 if (Op->isSubClassOf("Instruction")) {
128 Cost += Op->getValueAsInt("CodeSize");
129 }
130 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000131 Cost += getResultPatternSize(P->getChild(i), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000132 return Cost;
133}
134
Chris Lattner05814af2005-09-28 17:57:56 +0000135// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
136// In particular, we want to match maximal patterns first and lowest cost within
137// a particular complexity first.
138struct PatternSortingPredicate {
Chris Lattnerfe718932008-01-06 01:10:31 +0000139 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
140 CodeGenDAGPatterns &CGP;
Evan Cheng0fc71982005-12-08 02:00:36 +0000141
Dan Gohman0540e172008-10-15 06:17:21 +0000142 typedef std::pair<unsigned, std::string> CodeLine;
143 typedef std::vector<CodeLine> CodeList;
144 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
145
146 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
147 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
148 const PatternToMatch *LHS = LHSPair.first;
149 const PatternToMatch *RHS = RHSPair.first;
150
Chris Lattner6cefb772008-01-05 22:25:12 +0000151 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
152 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Evan Chengc81d2a02006-04-19 20:36:09 +0000153 LHSSize += LHS->getAddedComplexity();
154 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +0000155 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
156 if (LHSSize < RHSSize) return false;
157
158 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner6cefb772008-01-05 22:25:12 +0000159 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
160 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000161 if (LHSCost < RHSCost) return true;
162 if (LHSCost > RHSCost) return false;
163
Chris Lattner6cefb772008-01-05 22:25:12 +0000164 return getResultPatternSize(LHS->getDstPattern(), CGP) <
165 getResultPatternSize(RHS->getDstPattern(), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000166 }
167};
168
Jim Grosbach54f30222009-03-25 23:28:33 +0000169/// getRegisterValueType - Look up and return the ValueType of the specified
170/// register. If the register is a member of multiple register classes which
Owen Anderson825b72b2009-08-11 20:47:22 +0000171/// have different associated types, return MVT::Other.
Chris Lattner8e946be2010-02-21 03:22:59 +0000172static MVT::SimpleValueType getRegisterValueType(Record *R,
173 const CodeGenTarget &T) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000174 bool FoundRC = false;
Owen Anderson825b72b2009-08-11 20:47:22 +0000175 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000176 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
177 std::vector<CodeGenRegisterClass>::const_iterator RC;
178 std::vector<Record*>::const_iterator Element;
179
180 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
181 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
182 if (Element != (*RC).Elements.end()) {
183 if (!FoundRC) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000184 FoundRC = true;
Jim Grosbach54f30222009-03-25 23:28:33 +0000185 VT = (*RC).getValueTypeNum(0);
186 } else {
187 // In multiple RC's
188 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000189 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach54f30222009-03-25 23:28:33 +0000190 // target is responsible for handling this.
Owen Anderson825b72b2009-08-11 20:47:22 +0000191 return MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000192 }
193 }
194 }
195 }
196 return VT;
Evan Cheng66a48bb2005-12-01 00:18:45 +0000197}
198
Evan Chengf9d03182008-07-03 08:39:51 +0000199static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
200 return CGP.getSDNodeInfo(Op).getEnumName();
201}
202
Chris Lattnerdc32f982008-01-05 22:43:57 +0000203//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000204// Node Transformation emitter implementation.
205//
Daniel Dunbar1a551802009-07-03 00:10:29 +0000206void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner443e3f92008-01-05 22:54:53 +0000207 // Walk the pattern fragments, adding them to a map, which sorts them by
208 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000209 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000210 NXsByNameTy NXsByName;
211
Chris Lattnerfe718932008-01-06 01:10:31 +0000212 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000213 I != E; ++I)
214 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
215
216 OS << "\n// Node transformations.\n";
217
218 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
219 I != E; ++I) {
220 Record *SDNode = I->second.first;
221 std::string Code = I->second.second;
222
223 if (Code.empty()) continue; // Empty code? Skip it.
224
Chris Lattner200c57e2008-01-05 22:58:54 +0000225 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000226 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
227
Dan Gohman475871a2008-07-27 21:46:04 +0000228 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner443e3f92008-01-05 22:54:53 +0000229 << ") {\n";
230 if (ClassName != "SDNode")
231 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
232 OS << Code << "\n}\n";
233 }
234}
235
236//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000237// Predicate emitter implementation.
238//
239
Daniel Dunbar1a551802009-07-03 00:10:29 +0000240void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattnerdc32f982008-01-05 22:43:57 +0000241 OS << "\n// Predicate functions.\n";
242
243 // Walk the pattern fragments, adding them to a map, which sorts them by
244 // name.
245 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
246 PFsByNameTy PFsByName;
247
Chris Lattnerfe718932008-01-06 01:10:31 +0000248 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000249 I != E; ++I)
250 PFsByName.insert(std::make_pair(I->first->getName(), *I));
251
252
253 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
254 I != E; ++I) {
255 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
256 TreePattern *P = I->second.second;
257
258 // If there is a code init for this fragment, emit the predicate code.
259 std::string Code = PatFragRecord->getValueAsCode("Predicate");
260 if (Code.empty()) continue;
261
262 if (P->getOnlyTree()->isLeaf())
263 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattnerccba15f2010-02-16 07:26:36 +0000264 << "(SDNode *N) const {\n";
Chris Lattnerdc32f982008-01-05 22:43:57 +0000265 else {
266 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000267 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000268 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
269
270 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattnerccba15f2010-02-16 07:26:36 +0000271 << "(SDNode *" << C2 << ") const {\n";
Chris Lattnerdc32f982008-01-05 22:43:57 +0000272 if (ClassName != "SDNode")
273 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
274 }
275 OS << Code << "\n}\n";
276 }
277
278 OS << "\n\n";
279}
280
281
282//===----------------------------------------------------------------------===//
283// PatternCodeEmitter implementation.
284//
Evan Chengb915f312005-12-09 22:45:35 +0000285class PatternCodeEmitter {
286private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000287 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000288
Evan Cheng58e84a62005-12-14 22:02:59 +0000289 // Predicates.
Dan Gohman22bb3112008-08-22 00:20:26 +0000290 std::string PredicateCheck;
Evan Cheng59413202006-04-19 18:07:24 +0000291 // Pattern cost.
292 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000293 // Instruction selector pattern.
294 TreePatternNode *Pattern;
295 // Matched instruction.
296 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000297
Evan Chengb915f312005-12-09 22:45:35 +0000298 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000299 std::map<std::string, std::string> VariableMap;
Evan Chenga58891f2008-02-05 22:50:29 +0000300 // Name of the folded node which produces a flag.
301 std::pair<std::string, unsigned> FoldedFlag;
Evan Chengb915f312005-12-09 22:45:35 +0000302 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000303 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000304 // Original input chain(s).
305 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000306 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000307
Dan Gohman69de1932008-02-06 22:27:42 +0000308 /// LSI - Load/Store information.
309 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
310 /// for each memory access. This facilitates the use of AliasAnalysis in
311 /// the backend.
312 std::vector<std::string> LSI;
313
Evan Cheng676d7312006-08-26 00:59:04 +0000314 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000315 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000316 /// 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;
Dan Gohman475871a2008-07-27 21:46:04 +0000319 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Evan Cheng21ad3922006-02-07 00:37:41 +0000320 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000321 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000322 /// TargetOpcodes - The target specific opcodes used by the resulting
323 /// instructions.
324 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000325 std::vector<std::string> &TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000326 /// OutputIsVariadic - Records whether the instruction output pattern uses
327 /// variable_ops. This requires that the Emit function be passed an
328 /// additional argument to indicate where the input varargs operands
329 /// begin.
330 bool &OutputIsVariadic;
331 /// NumInputRootOps - Records the number of operands the root node of the
332 /// input pattern has. This information is used in the generated code to
333 /// pass to Emit functions when variable_ops processing is needed.
334 unsigned &NumInputRootOps;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000335
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000336 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000337 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000338 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000339 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000340
341 void emitCheck(const std::string &S) {
342 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000343 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000344 }
345 void emitCode(const std::string &S) {
346 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000347 GeneratedCode.push_back(std::make_pair(0, S));
348 }
349 void emitInit(const std::string &S) {
350 if (!S.empty())
351 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000352 }
Evan Chengf5493192006-08-26 01:02:19 +0000353 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000354 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000355 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000356 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000357 void emitOpcode(const std::string &Opc) {
358 TargetOpcodes.push_back(Opc);
359 OpcNo++;
360 }
Evan Chengf8729402006-07-16 06:12:52 +0000361 void emitVT(const std::string &VT) {
362 TargetVTs.push_back(VT);
363 VTNo++;
364 }
Evan Chengb915f312005-12-09 22:45:35 +0000365public:
Dan Gohman22bb3112008-08-22 00:20:26 +0000366 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Evan Cheng58e84a62005-12-14 22:02:59 +0000367 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000368 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000369 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000370 std::vector<std::string> &to,
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000371 std::vector<std::string> &tv,
372 bool &oiv,
373 unsigned &niro)
Dan Gohman22bb3112008-08-22 00:20:26 +0000374 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000375 GeneratedCode(gc), GeneratedDecl(gd),
376 TargetOpcodes(to), TargetVTs(tv),
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000377 OutputIsVariadic(oiv), NumInputRootOps(niro),
Chris Lattner706d2d32006-08-09 16:44:44 +0000378 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000379
380 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
381 /// if the match fails. At this point, we already know that the opcode for N
382 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000383 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
384 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000385 bool &FoundChain);
Chris Lattner39e73f72006-10-11 04:05:55 +0000386
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000387 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb85356242008-01-31 07:27:46 +0000388 const std::string &RootName,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000389 const std::string &ChainSuffix, bool &FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000390
391 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
392 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000393 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000394 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000395 bool InFlagDecled, bool ResNodeDecled,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000396 bool LikeLeaf = false, bool isRoot = false);
Evan Chengb915f312005-12-09 22:45:35 +0000397
Chris Lattner488580c2006-01-28 19:06:51 +0000398 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
399 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +0000400 /// 'Pat' may be missing types. If we find an unresolved type to add a check
401 /// for, this returns true otherwise false if Pat has all types.
402 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +0000403 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +0000404 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +0000405 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +0000406 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +0000407 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +0000408 // The top level node type is checked outside of the select function.
409 if (!isRoot)
Anton Korobeynikovc2fd9192009-11-08 12:14:54 +0000410 emitCheck(Prefix + ".getValueType() == " +
Chris Lattner706d2d32006-08-09 16:44:44 +0000411 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +0000412 return true;
Evan Chengb915f312005-12-09 22:45:35 +0000413 }
414
Chris Lattner47661322010-02-14 22:22:58 +0000415 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000416 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
417 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
418 Prefix + utostr(OpNo)))
419 return true;
420 return false;
421 }
422
423private:
Evan Cheng54597732006-01-26 00:22:25 +0000424 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +0000425 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +0000426 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +0000427 bool &ChainEmitted, bool &InFlagDecled,
428 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000429 const CodeGenTarget &T = CGP.getTargetInfo();
Chris Lattner47661322010-02-14 22:22:58 +0000430 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000431 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
432 TreePatternNode *Child = N->getChild(i);
433 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000434 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
435 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +0000436 } else {
437 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +0000438 if (!Child->getName().empty()) {
439 std::string Name = RootName + utostr(OpNo);
440 if (Duplicates.find(Name) != Duplicates.end())
441 // A duplicate! Do not emit a copy for this node.
442 continue;
443 }
444
Evan Chengb915f312005-12-09 22:45:35 +0000445 Record *RR = DI->getDef();
446 if (RR->isSubClassOf("Register")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000447 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
448 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000449 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000450 emitCode("SDValue InFlag = " +
451 getValueName(RootName + utostr(OpNo)) + ";");
Evan Cheng676d7312006-08-26 00:59:04 +0000452 InFlagDecled = true;
453 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000454 emitCode("InFlag = " +
455 getValueName(RootName + utostr(OpNo)) + ";");
Evan Chengb2c6d492006-01-11 22:16:13 +0000456 } else {
457 if (!ChainEmitted) {
Dan Gohman475871a2008-07-27 21:46:04 +0000458 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000459 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +0000460 ChainEmitted = true;
461 }
Evan Cheng676d7312006-08-26 00:59:04 +0000462 if (!InFlagDecled) {
Dan Gohman475871a2008-07-27 21:46:04 +0000463 emitCode("SDValue InFlag(0, 0);");
Evan Cheng676d7312006-08-26 00:59:04 +0000464 InFlagDecled = true;
465 }
Dale Johannesen874ae252009-06-02 03:12:52 +0000466 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
467 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000468 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000469 ", " + getQualifiedName(RR) +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000470 ", " + getValueName(RootName + utostr(OpNo)) +
471 ", InFlag).getNode();");
Dale Johannesen874ae252009-06-02 03:12:52 +0000472 ResNodeDecled = true;
Dan Gohman475871a2008-07-27 21:46:04 +0000473 emitCode(ChainName + " = SDValue(ResNode, 0);");
474 emitCode("InFlag = SDValue(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +0000475 }
476 }
477 }
478 }
479 }
Evan Cheng54597732006-01-26 00:22:25 +0000480
Chris Lattner8e946be2010-02-21 03:22:59 +0000481 if (N->NodeHasProperty(SDNPInFlag, CGP)) {
Evan Cheng676d7312006-08-26 00:59:04 +0000482 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000483 emitCode("SDValue InFlag = " + getNodeName(RootName) +
484 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000485 InFlagDecled = true;
486 } else
Chris Lattner8e946be2010-02-21 03:22:59 +0000487 abort();
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000488 emitCode("InFlag = " + getNodeName(RootName) +
489 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000490 }
Evan Chengb915f312005-12-09 22:45:35 +0000491 }
492};
493
Chris Lattnera0cdf172010-02-13 20:06:50 +0000494
495/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
496/// if the match fails. At this point, we already know that the opcode for N
497/// matches, and the SDNode for the result has the RootName specified name.
498void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
499 const std::string &RootName,
500 const std::string &ChainSuffix,
501 bool &FoundChain) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000502 // Save loads/stores matched by a pattern.
503 if (!N->isLeaf() && N->getName().empty()) {
Chris Lattner47661322010-02-14 22:22:58 +0000504 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnera0cdf172010-02-13 20:06:50 +0000505 LSI.push_back(getNodeName(RootName));
506 }
507
508 bool isRoot = (P == NULL);
509 // Emit instruction predicates. Each predicate is just a string for now.
510 if (isRoot) {
511 // Record input varargs info.
512 NumInputRootOps = N->getNumChildren();
Chris Lattnera0cdf172010-02-13 20:06:50 +0000513 emitCheck(PredicateCheck);
514 }
515
516 if (N->isLeaf()) {
517 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
518 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
519 ")->getSExtValue() == INT64_C(" +
520 itostr(II->getValue()) + ")");
521 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000522 }
Chris Lattner05446e72010-02-16 23:13:59 +0000523 assert(N->getComplexPatternInfo(CGP) != 0 &&
524 "Cannot match this as a leaf value!");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000525 }
526
527 // If this node has a name associated with it, capture it in VariableMap. If
528 // we already saw this in the pattern, emit code to verify dagness.
529 if (!N->getName().empty()) {
530 std::string &VarMapEntry = VariableMap[N->getName()];
531 if (VarMapEntry.empty()) {
532 VarMapEntry = RootName;
533 } else {
534 // If we get here, this is a second reference to a specific name. Since
535 // we already have checked that the first reference is valid, we don't
536 // have to recursively match it, just check that it's the same as the
537 // previously named thing.
538 emitCheck(VarMapEntry + " == " + RootName);
539 return;
540 }
Chris Lattnera0cdf172010-02-13 20:06:50 +0000541 }
542
543
544 // Emit code to load the child nodes and match their contents recursively.
545 unsigned OpNo = 0;
Chris Lattner47661322010-02-14 22:22:58 +0000546 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
547 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000548 if (HasChain) {
549 if (NodeHasChain)
550 OpNo = 1;
551 if (!isRoot) {
Evan Cheng014bf212010-02-15 19:41:07 +0000552 // Check if it's profitable to fold the node. e.g. Check for multiple uses
553 // of actual result?
554 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner29c62702010-02-16 19:03:34 +0000555 if (!NodeHasChain) {
556 // If this is just an interior node, check to see if it has a single
557 // use. If the node has multiple uses and the pattern has a load as
558 // an operand, then we can't fold the load.
559 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattner92d3ada2010-02-16 22:35:06 +0000560 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000561 // If the immediate use can somehow reach this node through another
562 // path, then can't fold it either or it will create a cycle.
563 // e.g. In the following diagram, XX can reach ld through YY. If
564 // ld is folded into XX, then YY is both a predecessor and a successor
565 // of XX.
566 //
567 // [ld]
568 // ^ ^
569 // | |
570 // / \---
571 // / [YY]
572 // | ^
573 // [XX]-------|
Chris Lattnere39650a2010-02-16 06:10:58 +0000574
575 // We know we need the check if N's parent is not the root.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000576 bool NeedCheck = P != Pattern;
577 if (!NeedCheck) {
Chris Lattner29c62702010-02-16 19:03:34 +0000578 // If the parent is the root and the node has more than one operand,
579 // we need to check.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000580 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
581 NeedCheck =
582 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
583 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
584 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
585 PInfo.getNumOperands() > 1 ||
586 PInfo.hasProperty(SDNPHasChain) ||
587 PInfo.hasProperty(SDNPInFlag) ||
588 PInfo.hasProperty(SDNPOptInFlag);
589 }
590
591 if (NeedCheck) {
Chris Lattner29c62702010-02-16 19:03:34 +0000592 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
593 ", " + getNodeName(ParentName) + ", N)");
Evan Cheng014bf212010-02-15 19:41:07 +0000594 emitCheck("IsLegalToFold(" + getValueName(RootName) +
Chris Lattnera0cdf172010-02-13 20:06:50 +0000595 ", " + getNodeName(ParentName) + ", N)");
Chris Lattner29c62702010-02-16 19:03:34 +0000596 } else {
597 // Otherwise, just verify that the node only has a single use.
598 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000599 }
600 }
601 }
602
603 if (NodeHasChain) {
604 if (FoundChain) {
Chris Lattnerd9c1a342010-02-17 05:35:28 +0000605 emitCheck("IsChainCompatible(" + ChainName + ".getNode(), " +
606 getNodeName(RootName) + ")");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000607 OrigChains.push_back(std::make_pair(ChainName,
608 getValueName(RootName)));
609 } else
610 FoundChain = true;
611 ChainName = "Chain" + ChainSuffix;
Chris Lattner92d3ada2010-02-16 22:35:06 +0000612
613 if (!N->getComplexPatternInfo(CGP) ||
614 isRoot)
615 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
616 "->getOperand(0);");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000617 }
618 }
619
Chris Lattnera0cdf172010-02-13 20:06:50 +0000620 // If there are node predicates for this, emit the calls.
621 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
622 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
623
624 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
625 // a constant without a predicate fn that has more that one bit set, handle
626 // this as a special case. This is usually for targets that have special
627 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
628 // handling stuff). Using these instructions is often far more efficient
629 // than materializing the constant. Unfortunately, both the instcombiner
630 // and the dag combiner can often infer that bits are dead, and thus drop
631 // them from the mask in the dag. For example, it might turn 'AND X, 255'
632 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
633 // to handle this.
634 if (!N->isLeaf() &&
635 (N->getOperator()->getName() == "and" ||
636 N->getOperator()->getName() == "or") &&
637 N->getChild(1)->isLeaf() &&
638 N->getChild(1)->getPredicateFns().empty()) {
639 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
640 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
641 emitInit("SDValue " + RootName + "0" + " = " +
642 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
643 emitInit("SDValue " + RootName + "1" + " = " +
644 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
645
646 unsigned NTmp = TmpNo++;
647 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
648 " = dyn_cast<ConstantSDNode>(" +
649 getNodeName(RootName + "1") + ");");
650 emitCheck("Tmp" + utostr(NTmp));
651 const char *MaskPredicate = N->getOperator()->getName() == "or"
652 ? "CheckOrMask(" : "CheckAndMask(";
653 emitCheck(MaskPredicate + getValueName(RootName + "0") +
654 ", Tmp" + utostr(NTmp) +
655 ", INT64_C(" + itostr(II->getValue()) + "))");
656
657 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
658 ChainSuffix + utostr(0), FoundChain);
659 return;
660 }
661 }
662 }
663
664 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
665 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
666 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
667
668 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
669 ChainSuffix + utostr(OpNo), FoundChain);
670 }
671
Chris Lattner8e946be2010-02-21 03:22:59 +0000672 // Handle complex patterns.
673 if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000674 std::string Fn = CP->getSelectFunc();
675 unsigned NumOps = CP->getNumOperands();
676 for (unsigned i = 0; i < NumOps; ++i) {
677 emitDecl("CPTmp" + RootName + "_" + utostr(i));
678 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
679 }
680 if (CP->hasProperty(SDNPHasChain)) {
681 emitDecl("CPInChain");
682 emitDecl("Chain" + ChainSuffix);
683 emitCode("SDValue CPInChain;");
684 emitCode("SDValue Chain" + ChainSuffix + ";");
685 }
686
Chris Lattner92d3ada2010-02-16 22:35:06 +0000687 std::string Code = Fn + "(N, "; // always pass in the root.
688 Code += getValueName(RootName);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000689 for (unsigned i = 0; i < NumOps; i++)
690 Code += ", CPTmp" + RootName + "_" + utostr(i);
691 if (CP->hasProperty(SDNPHasChain)) {
692 ChainName = "Chain" + ChainSuffix;
Chris Lattnere609a512010-02-17 00:31:50 +0000693 Code += ", CPInChain, " + ChainName;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000694 }
695 emitCheck(Code + ")");
696 }
697}
698
699void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
700 TreePatternNode *Parent,
701 const std::string &RootName,
702 const std::string &ChainSuffix,
703 bool &FoundChain) {
704 if (!Child->isLeaf()) {
705 // If it's not a leaf, recursively match.
706 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
707 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
708 CInfo.getEnumName());
709 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
710 bool HasChain = false;
Chris Lattner47661322010-02-14 22:22:58 +0000711 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000712 HasChain = true;
713 FoldedChains.push_back(std::make_pair(getValueName(RootName),
714 CInfo.getNumResults()));
715 }
Chris Lattner47661322010-02-14 22:22:58 +0000716 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000717 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
718 "Pattern folded multiple nodes which produce flags?");
719 FoldedFlag = std::make_pair(getValueName(RootName),
720 CInfo.getNumResults() + (unsigned)HasChain);
721 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000722 return;
723 }
724
725 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
Chris Lattner92d3ada2010-02-16 22:35:06 +0000726 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
727 bool HasChain = false;
728
729 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
730 HasChain = true;
731 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
732 FoldedChains.push_back(std::make_pair("CPInChain",
733 PInfo.getNumResults()));
734 }
735 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
736 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
737 "Pattern folded multiple nodes which produce flags?");
738 FoldedFlag = std::make_pair(getValueName(RootName),
739 CP->getNumOperands() + (unsigned)HasChain);
740 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000741 return;
742 }
743
744 // If this child has a name associated with it, capture it in VarMap. If
745 // we already saw this in the pattern, emit code to verify dagness.
746 if (!Child->getName().empty()) {
747 std::string &VarMapEntry = VariableMap[Child->getName()];
748 if (VarMapEntry.empty()) {
749 VarMapEntry = getValueName(RootName);
750 } else {
751 // If we get here, this is a second reference to a specific name.
752 // Since we already have checked that the first reference is valid,
753 // we don't have to recursively match it, just check that it's the
754 // same as the previously named thing.
755 emitCheck(VarMapEntry + " == " + getValueName(RootName));
756 Duplicates.insert(getValueName(RootName));
757 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000758 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000759 }
760
761 // Handle leaves of various types.
762 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
763 Record *LeafRec = DI->getDef();
764 if (LeafRec->isSubClassOf("RegisterClass") ||
765 LeafRec->isSubClassOf("PointerLikeRegClass")) {
766 // Handle register references. Nothing to do here.
767 } else if (LeafRec->isSubClassOf("Register")) {
768 // Handle register references.
769 } else if (LeafRec->getName() == "srcvalue") {
770 // Place holder for SRCVALUE nodes. Nothing to do here.
771 } else if (LeafRec->isSubClassOf("ValueType")) {
772 // Make sure this is the specified value type.
773 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
774 ")->getVT() == MVT::" + LeafRec->getName());
775 } else if (LeafRec->isSubClassOf("CondCode")) {
776 // Make sure this is the specified cond code.
777 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
778 ")->get() == ISD::" + LeafRec->getName());
Chris Lattnera0cdf172010-02-13 20:06:50 +0000779 } else {
780#ifndef NDEBUG
781 Child->dump();
Chris Lattner5b08f772010-02-16 22:38:31 +0000782 errs() << " ";
Chris Lattnera0cdf172010-02-13 20:06:50 +0000783#endif
784 assert(0 && "Unknown leaf type!");
785 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000786
787 // If there are node predicates for this, emit the calls.
788 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
789 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
790 ")");
791 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000792 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000793
794 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
795 unsigned NTmp = TmpNo++;
796 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
797 " = dyn_cast<ConstantSDNode>("+
798 getNodeName(RootName) + ");");
799 emitCheck("Tmp" + utostr(NTmp));
800 unsigned CTmp = TmpNo++;
801 emitCode("int64_t CN"+ utostr(CTmp) +
802 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
803 emitCheck("CN" + utostr(CTmp) + " == "
804 "INT64_C(" +itostr(II->getValue()) + ")");
805 return;
806 }
807#ifndef NDEBUG
808 Child->dump();
809#endif
810 assert(0 && "Unknown leaf type!");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000811}
812
813/// EmitResultCode - Emit the action for a pattern. Now that it has matched
814/// we actually have to build a DAG!
815std::vector<std::string>
816PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
817 std::vector<Record*> DstRegs,
818 bool InFlagDecled, bool ResNodeDecled,
819 bool LikeLeaf, bool isRoot) {
820 // List of arguments of getMachineNode() or SelectNodeTo().
821 std::vector<std::string> NodeOps;
822 // This is something selected from the pattern we matched.
823 if (!N->getName().empty()) {
824 const std::string &VarName = N->getName();
825 std::string Val = VariableMap[VarName];
Chris Lattnera0cdf172010-02-13 20:06:50 +0000826 if (Val.empty()) {
827 errs() << "Variable '" << VarName << " referenced but not defined "
828 << "and not caught earlier!\n";
829 abort();
830 }
Chris Lattnera0cdf172010-02-13 20:06:50 +0000831
Chris Lattnera0cdf172010-02-13 20:06:50 +0000832 unsigned ResNo = TmpNo++;
833 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
834 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
835 std::string CastType;
836 std::string TmpVar = "Tmp" + utostr(ResNo);
837 switch (N->getTypeNum(0)) {
838 default:
839 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
840 << " type as an immediate constant. Aborting\n";
841 abort();
842 case MVT::i1: CastType = "bool"; break;
843 case MVT::i8: CastType = "unsigned char"; break;
844 case MVT::i16: CastType = "unsigned short"; break;
845 case MVT::i32: CastType = "unsigned"; break;
846 case MVT::i64: CastType = "uint64_t"; break;
847 }
848 emitCode("SDValue " + TmpVar +
849 " = CurDAG->getTargetConstant(((" + CastType +
850 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
851 getEnumName(N->getTypeNum(0)) + ");");
Chris Lattner8e946be2010-02-21 03:22:59 +0000852 NodeOps.push_back(getValueName(TmpVar));
Chris Lattnera0cdf172010-02-13 20:06:50 +0000853 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
854 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
855 std::string TmpVar = "Tmp" + utostr(ResNo);
856 emitCode("SDValue " + TmpVar +
857 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
858 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
859 Val + ")->getValueType(0));");
Chris Lattner8e946be2010-02-21 03:22:59 +0000860 NodeOps.push_back(getValueName(TmpVar));
861 } else if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
862 for (unsigned i = 0; i < CP->getNumOperands(); ++i)
Chris Lattner47661322010-02-14 22:22:58 +0000863 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
Chris Lattner47661322010-02-14 22:22:58 +0000864 } else {
865 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
866 // node even if it isn't one. Don't select it.
867 if (!LikeLeaf) {
868 if (isRoot && N->isLeaf()) {
869 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
870 emitCode("return NULL;");
871 }
872 }
873 NodeOps.push_back(getValueName(Val));
Chris Lattnera0cdf172010-02-13 20:06:50 +0000874 }
875 return NodeOps;
876 }
877 if (N->isLeaf()) {
878 // If this is an explicit register reference, handle it.
879 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
880 unsigned ResNo = TmpNo++;
881 if (DI->getDef()->isSubClassOf("Register")) {
882 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
883 getQualifiedName(DI->getDef()) + ", " +
884 getEnumName(N->getTypeNum(0)) + ");");
885 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
886 return NodeOps;
887 } else if (DI->getDef()->getName() == "zero_reg") {
888 emitCode("SDValue Tmp" + utostr(ResNo) +
889 " = CurDAG->getRegister(0, " +
890 getEnumName(N->getTypeNum(0)) + ");");
891 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
892 return NodeOps;
893 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
894 // Handle a reference to a register class. This is used
895 // in COPY_TO_SUBREG instructions.
896 emitCode("SDValue Tmp" + utostr(ResNo) +
897 " = CurDAG->getTargetConstant(" +
898 getQualifiedName(DI->getDef()) + "RegClassID, " +
899 "MVT::i32);");
900 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
901 return NodeOps;
902 }
903 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
904 unsigned ResNo = TmpNo++;
905 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
906 emitCode("SDValue Tmp" + utostr(ResNo) +
907 " = CurDAG->getTargetConstant(0x" +
908 utohexstr((uint64_t) II->getValue()) +
909 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
910 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
911 return NodeOps;
912 }
913
914#ifndef NDEBUG
915 N->dump();
916#endif
917 assert(0 && "Unknown leaf type!");
918 return NodeOps;
919 }
920
921 Record *Op = N->getOperator();
922 if (Op->isSubClassOf("Instruction")) {
923 const CodeGenTarget &CGT = CGP.getTargetInfo();
924 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
925 const DAGInstruction &Inst = CGP.getInstruction(Op);
926 const TreePattern *InstPat = Inst.getPattern();
927 // FIXME: Assume actual pattern comes before "implicit".
928 TreePatternNode *InstPatNode =
929 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
930 : (InstPat ? InstPat->getTree(0) : NULL);
931 if (InstPatNode && !InstPatNode->isLeaf() &&
932 InstPatNode->getOperator()->getName() == "set") {
933 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
934 }
935 bool IsVariadic = isRoot && II.isVariadic;
936 // FIXME: fix how we deal with physical register operands.
937 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
938 bool HasImpResults = isRoot && DstRegs.size() > 0;
939 bool NodeHasOptInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000940 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000941 bool NodeHasInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000942 Pattern->TreeHasProperty(SDNPInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000943 bool NodeHasOutFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +0000944 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000945 bool NodeHasChain = InstPatNode &&
Chris Lattner47661322010-02-14 22:22:58 +0000946 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
947 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000948 unsigned NumResults = Inst.getNumResults();
949 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
950
951 // Record output varargs info.
952 OutputIsVariadic = IsVariadic;
953
954 if (NodeHasOptInFlag) {
955 emitCode("bool HasInFlag = "
956 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
957 "MVT::Flag);");
958 }
959 if (IsVariadic)
960 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
Chris Lattnerb49985a2010-02-18 06:47:49 +0000961
Chris Lattnera0cdf172010-02-13 20:06:50 +0000962 // How many results is this pattern expected to produce?
963 unsigned NumPatResults = 0;
964 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
965 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
966 if (VT != MVT::isVoid && VT != MVT::Flag)
967 NumPatResults++;
968 }
969
970 if (OrigChains.size() > 0) {
971 // The original input chain is being ignored. If it is not just
972 // pointing to the op that's being folded, we should create a
973 // TokenFactor with it and the chain of the folded op as the new chain.
974 // We could potentially be doing multiple levels of folding, in that
975 // case, the TokenFactor can have more operands.
976 emitCode("SmallVector<SDValue, 8> InChains;");
977 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
978 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
979 OrigChains[i].second + ".getNode()) {");
980 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
981 emitCode("}");
982 }
983 emitCode("InChains.push_back(" + ChainName + ");");
984 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
985 "N->getDebugLoc(), MVT::Other, "
986 "&InChains[0], InChains.size());");
987 if (GenDebug) {
Chris Lattnerdcdcef22010-02-18 00:23:27 +0000988 emitCode("CurDAG->setSubgraphColor(" + ChainName +
989 ".getNode(), \"yellow\");");
990 emitCode("CurDAG->setSubgraphColor(" + ChainName +
991 ".getNode(), \"black\");");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000992 }
993 }
994
995 // Loop over all of the operands of the instruction pattern, emitting code
996 // to fill them all in. The node 'N' usually has number children equal to
997 // the number of input operands of the instruction. However, in cases
998 // where there are predicate operands for an instruction, we need to fill
999 // in the 'execute always' values. Match up the node operands to the
1000 // instruction operands to do this.
1001 std::vector<std::string> AllOps;
1002 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1003 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1004 std::vector<std::string> Ops;
1005
1006 // Determine what to emit for this operand.
1007 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1008 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1009 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1010 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1011 // This is a predicate or optional def operand; emit the
1012 // 'default ops' operands.
1013 const DAGDefaultOperand &DefaultOp =
1014 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1015 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1016 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1017 InFlagDecled, ResNodeDecled);
1018 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1019 }
1020 } else {
1021 // Otherwise this is a normal operand or a predicate operand without
1022 // 'execute always'; emit it.
1023 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1024 InFlagDecled, ResNodeDecled);
1025 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1026 ++ChildNo;
1027 }
1028 }
1029
1030 // Emit all the chain and CopyToReg stuff.
1031 bool ChainEmitted = NodeHasChain;
1032 if (NodeHasInFlag || HasImpInputs)
1033 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1034 InFlagDecled, ResNodeDecled, true);
1035 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1036 if (!InFlagDecled) {
1037 emitCode("SDValue InFlag(0, 0);");
1038 InFlagDecled = true;
1039 }
1040 if (NodeHasOptInFlag) {
1041 emitCode("if (HasInFlag) {");
1042 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1043 emitCode("}");
1044 }
1045 }
1046
1047 unsigned ResNo = TmpNo++;
1048
1049 unsigned OpsNo = OpcNo;
1050 std::string CodePrefix;
1051 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1052 std::deque<std::string> After;
1053 std::string NodeName;
1054 if (!isRoot) {
1055 NodeName = "Tmp" + utostr(ResNo);
1056 CodePrefix = "SDValue " + NodeName + "(";
1057 } else {
1058 NodeName = "ResNode";
1059 if (!ResNodeDecled) {
1060 CodePrefix = "SDNode *" + NodeName + " = ";
1061 ResNodeDecled = true;
1062 } else
1063 CodePrefix = NodeName + " = ";
1064 }
1065
1066 std::string Code = "Opc" + utostr(OpcNo);
1067
1068 if (!isRoot || (InputHasChain && !NodeHasChain))
1069 // For call to "getMachineNode()".
1070 Code += ", N->getDebugLoc()";
1071
1072 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1073
1074 // Output order: results, chain, flags
1075 // Result types.
1076 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1077 Code += ", VT" + utostr(VTNo);
1078 emitVT(getEnumName(N->getTypeNum(0)));
1079 }
1080 // Add types for implicit results in physical registers, scheduler will
1081 // care of adding copyfromreg nodes.
1082 for (unsigned i = 0; i < NumDstRegs; i++) {
1083 Record *RR = DstRegs[i];
1084 if (RR->isSubClassOf("Register")) {
1085 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1086 Code += ", " + getEnumName(RVT);
1087 }
1088 }
1089 if (NodeHasChain)
1090 Code += ", MVT::Other";
1091 if (NodeHasOutFlag)
1092 Code += ", MVT::Flag";
1093
1094 // Inputs.
1095 if (IsVariadic) {
1096 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1097 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1098 AllOps.clear();
1099
1100 // Figure out whether any operands at the end of the op list are not
1101 // part of the variable section.
1102 std::string EndAdjust;
1103 if (NodeHasInFlag || HasImpInputs)
1104 EndAdjust = "-1"; // Always has one flag.
1105 else if (NodeHasOptInFlag)
1106 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1107
1108 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1109 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1110
1111 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1112 emitCode("}");
1113 }
1114
1115 // Populate MemRefs with entries for each memory accesses covered by
1116 // this pattern.
1117 if (isRoot && !LSI.empty()) {
1118 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1119 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1120 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1121 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1122 emitCode(MemRefs + "[" + utostr(i) + "] = "
1123 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1124 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1125 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1126 ");");
1127 }
1128
1129 if (NodeHasChain) {
1130 if (IsVariadic)
1131 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1132 else
1133 AllOps.push_back(ChainName);
1134 }
1135
1136 if (IsVariadic) {
1137 if (NodeHasInFlag || HasImpInputs)
1138 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1139 else if (NodeHasOptInFlag) {
1140 emitCode("if (HasInFlag)");
1141 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1142 }
1143 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1144 ".size()";
1145 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1146 AllOps.push_back("InFlag");
1147
1148 unsigned NumOps = AllOps.size();
1149 if (NumOps) {
1150 if (!NodeHasOptInFlag && NumOps < 4) {
1151 for (unsigned i = 0; i != NumOps; ++i)
1152 Code += ", " + AllOps[i];
1153 } else {
1154 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1155 for (unsigned i = 0; i != NumOps; ++i) {
1156 OpsCode += AllOps[i];
1157 if (i != NumOps-1)
1158 OpsCode += ", ";
1159 }
1160 emitCode(OpsCode + " };");
1161 Code += ", Ops" + utostr(OpsNo) + ", ";
1162 if (NodeHasOptInFlag) {
1163 Code += "HasInFlag ? ";
1164 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1165 } else
1166 Code += utostr(NumOps);
1167 }
1168 }
1169
1170 if (!isRoot)
1171 Code += "), 0";
1172
1173 std::vector<std::string> ReplaceFroms;
1174 std::vector<std::string> ReplaceTos;
1175 if (!isRoot) {
1176 NodeOps.push_back("Tmp" + utostr(ResNo));
1177 } else {
1178
1179 if (NodeHasOutFlag) {
1180 if (!InFlagDecled) {
1181 After.push_back("SDValue InFlag(ResNode, " +
1182 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1183 ");");
1184 InFlagDecled = true;
1185 } else
1186 After.push_back("InFlag = SDValue(ResNode, " +
1187 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1188 ");");
1189 }
1190
1191 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1192 ReplaceFroms.push_back("SDValue(" +
1193 FoldedChains[j].first + ".getNode(), " +
1194 utostr(FoldedChains[j].second) +
1195 ")");
1196 ReplaceTos.push_back("SDValue(ResNode, " +
1197 utostr(NumResults+NumDstRegs) + ")");
1198 }
1199
1200 if (NodeHasOutFlag) {
1201 if (FoldedFlag.first != "") {
1202 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1203 utostr(FoldedFlag.second) + ")");
1204 ReplaceTos.push_back("InFlag");
1205 } else {
Chris Lattner47661322010-02-14 22:22:58 +00001206 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
Chris Lattnera0cdf172010-02-13 20:06:50 +00001207 ReplaceFroms.push_back("SDValue(N, " +
1208 utostr(NumPatResults + (unsigned)InputHasChain)
1209 + ")");
1210 ReplaceTos.push_back("InFlag");
1211 }
1212 }
1213
1214 if (!ReplaceFroms.empty() && InputHasChain) {
1215 ReplaceFroms.push_back("SDValue(N, " +
1216 utostr(NumPatResults) + ")");
1217 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1218 ChainName + ".getResNo()" + ")");
1219 ChainAssignmentNeeded |= NodeHasChain;
1220 }
1221
1222 // User does not expect the instruction would produce a chain!
1223 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1224 ;
1225 } else if (InputHasChain && !NodeHasChain) {
1226 // One of the inner node produces a chain.
1227 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1228 ReplaceFroms.push_back("SDValue(N, " +
1229 utostr(NumPatResults) + ")");
1230 ReplaceTos.push_back(ChainName);
1231 }
1232 }
1233
1234 if (ChainAssignmentNeeded) {
1235 // Remember which op produces the chain.
1236 std::string ChainAssign;
1237 if (!isRoot)
1238 ChainAssign = ChainName + " = SDValue(" + NodeName +
1239 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1240 else
1241 ChainAssign = ChainName + " = SDValue(" + NodeName +
1242 ", " + utostr(NumResults+NumDstRegs) + ");";
1243
1244 After.push_front(ChainAssign);
1245 }
1246
1247 if (ReplaceFroms.size() == 1) {
1248 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1249 ReplaceTos[0] + ");");
1250 } else if (!ReplaceFroms.empty()) {
1251 After.push_back("const SDValue Froms[] = {");
1252 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1253 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1254 After.push_back("};");
1255 After.push_back("const SDValue Tos[] = {");
1256 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1257 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1258 After.push_back("};");
1259 After.push_back("ReplaceUses(Froms, Tos, " +
1260 itostr(ReplaceFroms.size()) + ");");
1261 }
1262
1263 // We prefer to use SelectNodeTo since it avoids allocation when
1264 // possible and it avoids CSE map recalculation for the node's
1265 // users, however it's tricky to use in a non-root context.
1266 //
1267 // We also don't use SelectNodeTo if the pattern replacement is being
1268 // used to jettison a chain result, since morphing the node in place
1269 // would leave users of the chain dangling.
1270 //
1271 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1272 Code = "CurDAG->getMachineNode(" + Code;
1273 } else {
1274 Code = "CurDAG->SelectNodeTo(N, " + Code;
1275 }
1276 if (isRoot) {
1277 if (After.empty())
1278 CodePrefix = "return ";
1279 else
1280 After.push_back("return ResNode;");
1281 }
1282
1283 emitCode(CodePrefix + Code + ");");
1284
1285 if (GenDebug) {
1286 if (!isRoot) {
1287 emitCode("CurDAG->setSubgraphColor(" +
1288 NodeName +".getNode(), \"yellow\");");
1289 emitCode("CurDAG->setSubgraphColor(" +
1290 NodeName +".getNode(), \"black\");");
1291 } else {
1292 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1293 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1294 }
1295 }
1296
1297 for (unsigned i = 0, e = After.size(); i != e; ++i)
1298 emitCode(After[i]);
1299
1300 return NodeOps;
1301 }
1302 if (Op->isSubClassOf("SDNodeXForm")) {
1303 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1304 // PatLeaf node - the operand may or may not be a leaf node. But it should
1305 // behave like one.
1306 std::vector<std::string> Ops =
1307 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1308 ResNodeDecled, true);
1309 unsigned ResNo = TmpNo++;
1310 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1311 + "(" + Ops.back() + ".getNode());");
1312 NodeOps.push_back("Tmp" + utostr(ResNo));
1313 if (isRoot)
1314 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1315 return NodeOps;
1316 }
1317
1318 N->dump();
1319 errs() << "\n";
1320 throw std::string("Unknown node in result pattern!");
1321}
1322
1323
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001324/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1325/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001326/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001327void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001328 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001329 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001330 std::vector<std::string> &TargetOpcodes,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001331 std::vector<std::string> &TargetVTs,
1332 bool &OutputIsVariadic,
1333 unsigned &NumInputRootOps) {
1334 OutputIsVariadic = false;
1335 NumInputRootOps = 0;
1336
Dan Gohman22bb3112008-08-22 00:20:26 +00001337 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001338 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001339 GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001340 TargetOpcodes, TargetVTs,
1341 OutputIsVariadic, NumInputRootOps);
Evan Chengb915f312005-12-09 22:45:35 +00001342
Chris Lattner8fc35682005-09-23 23:16:51 +00001343 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001344 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001345 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001346
Chris Lattnerc87bf382010-02-14 21:11:53 +00001347 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1348 // diagnostics, which we know are impossible at this point.
Chris Lattner200c57e2008-01-05 22:58:54 +00001349 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001350
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001351 // At this point, we know that we structurally match the pattern, but the
1352 // types of the nodes may not match. Figure out the fewest number of type
1353 // comparisons we need to emit. For example, if there is only one integer
1354 // type supported by a target, there should be no type comparisons at all for
1355 // integer patterns!
1356 //
1357 // To figure out the fewest number of type checks needed, clone the pattern,
1358 // remove the types, then perform type inference on the pattern as a whole.
1359 // If there are unresolved types, emit an explicit check for those types,
1360 // apply the type to the tree, then rerun type inference. Iterate until all
1361 // types are resolved.
1362 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001363 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner47661322010-02-14 22:22:58 +00001364 Pat->RemoveAllTypes();
Chris Lattner7e82f132005-10-15 21:34:21 +00001365
1366 do {
1367 // Resolve/propagate as many types as possible.
1368 try {
1369 bool MadeChange = true;
1370 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001371 MadeChange = Pat->ApplyTypeConstraints(TP,
1372 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001373 } catch (...) {
1374 assert(0 && "Error: could not find consistent types for something we"
1375 " already decided was ok!");
1376 abort();
1377 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001378
Chris Lattner7e82f132005-10-15 21:34:21 +00001379 // Insert a check for an unresolved type and add it to the tree. If we find
1380 // an unresolved type to add a check for, this returns true and we iterate,
1381 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001382 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001383
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001384 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001385 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001386 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001387}
1388
Chris Lattner24e00a42006-01-29 04:41:05 +00001389/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1390/// a line causes any of them to be empty, remove them and return true when
1391/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001392static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001393 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001394 &Patterns) {
1395 bool ErasedPatterns = false;
1396 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1397 Patterns[i].second.pop_back();
1398 if (Patterns[i].second.empty()) {
1399 Patterns.erase(Patterns.begin()+i);
1400 --i; --e;
1401 ErasedPatterns = true;
1402 }
1403 }
1404 return ErasedPatterns;
1405}
1406
Chris Lattner8bc74722006-01-29 04:25:26 +00001407/// EmitPatterns - Emit code for at least one pattern, but try to group common
1408/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001409void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001410 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001411 &Patterns, unsigned Indent,
Daniel Dunbar1a551802009-07-03 00:10:29 +00001412 raw_ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001413 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001414 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001415 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001416
1417 if (Patterns.empty()) return;
1418
Chris Lattner24e00a42006-01-29 04:41:05 +00001419 // Figure out how many patterns share the next code line. Explicitly copy
1420 // FirstCodeLine so that we don't invalidate a reference when changing
1421 // Patterns.
1422 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001423 unsigned LastMatch = Patterns.size()-1;
1424 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1425 --LastMatch;
1426
1427 // If not all patterns share this line, split the list into two pieces. The
1428 // first chunk will use this line, the second chunk won't.
1429 if (LastMatch != 0) {
1430 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1431 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1432
1433 // FIXME: Emit braces?
1434 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001435 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001436 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1437 Pattern.getSrcPattern()->print(OS);
1438 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1439 Pattern.getDstPattern()->print(OS);
1440 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001441 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001442 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001443 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001444 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001445 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001446 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001447 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001448 }
Evan Cheng676d7312006-08-26 00:59:04 +00001449 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001450 OS << std::string(Indent, ' ') << "{\n";
1451 Indent += 2;
1452 }
1453 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001454 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001455 Indent -= 2;
1456 OS << std::string(Indent, ' ') << "}\n";
1457 }
1458
1459 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001460 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001461 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1462 Pattern.getSrcPattern()->print(OS);
1463 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1464 Pattern.getDstPattern()->print(OS);
1465 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001466 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001467 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001468 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001469 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001470 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001471 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001472 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001473 }
1474 EmitPatterns(Other, Indent, OS);
1475 return;
1476 }
1477
Chris Lattner24e00a42006-01-29 04:41:05 +00001478 // Remove this code from all of the patterns that share it.
1479 bool ErasedPatterns = EraseCodeLine(Patterns);
1480
Evan Cheng676d7312006-08-26 00:59:04 +00001481 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001482
1483 // Otherwise, every pattern in the list has this line. Emit it.
1484 if (!isPredicate) {
1485 // Normal code.
1486 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1487 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001488 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1489
1490 // If the next code line is another predicate, and if all of the pattern
1491 // in this group share the same next line, emit it inline now. Do this
1492 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001493 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00001494 // Check that all of the patterns in Patterns end with the same predicate.
Chris Lattner24e00a42006-01-29 04:41:05 +00001495 bool AllEndWithSamePredicate = true;
1496 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1497 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1498 AllEndWithSamePredicate = false;
1499 break;
1500 }
1501 // If all of the predicates aren't the same, we can't share them.
1502 if (!AllEndWithSamePredicate) break;
1503
1504 // Otherwise we can. Emit it shared now.
1505 OS << " &&\n" << std::string(Indent+4, ' ')
1506 << Patterns.back().second.back().second;
1507 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001508 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001509
1510 OS << ") {\n";
1511 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001512 }
1513
1514 EmitPatterns(Patterns, Indent, OS);
1515
1516 if (isPredicate)
1517 OS << std::string(Indent-2, ' ') << "}\n";
1518}
1519
Evan Cheng892aaf82006-11-08 23:01:03 +00001520static std::string getLegalCName(std::string OpName) {
1521 std::string::size_type pos = OpName.find("::");
1522 if (pos != std::string::npos)
1523 OpName.replace(pos, 2, "_");
1524 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001525}
1526
Daniel Dunbar1a551802009-07-03 00:10:29 +00001527void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001528 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattnerda272d12010-02-15 08:04:42 +00001529
Dan Gohman1e0ee4b2008-08-20 21:45:57 +00001530 // Get the namespace to insert instructions into.
1531 std::string InstNS = Target.getInstNamespace();
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001532 if (!InstNS.empty()) InstNS += "::";
1533
Chris Lattner602f6922006-01-04 00:25:00 +00001534 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001535 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001536 // All unique target node emission functions.
1537 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001538 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001539 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001540 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001541 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001542 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001543 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001544 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001545 } else {
1546 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001547 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001548 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001549 push_back(&Pattern);
Chris Lattner47661322010-02-14 22:22:58 +00001550 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001551 std::vector<Record*> OpNodes = CP->getRootNodes();
1552 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001553 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1554 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001555 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001556 }
1557 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001558 errs() << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001559 Node->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001560 errs() << "' on tree pattern '";
1561 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001562 exit(1);
1563 }
1564 }
1565 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001566
1567 // For each opcode, there might be multiple select functions, one per
1568 // ValueType of the node (or its first operand if it doesn't produce a
1569 // non-chain result.
1570 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1571
Chris Lattner602f6922006-01-04 00:25:00 +00001572 // Emit one Select_* method for each top-level opcode. We do this instead of
1573 // emitting one giant switch statement to support compilers where this will
1574 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001575 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001576 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1577 PBOI != E; ++PBOI) {
1578 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001579 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001580 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1581
Chris Lattner706d2d32006-08-09 16:44:44 +00001582 // Split them into groups by type.
Owen Anderson825b72b2009-08-11 20:47:22 +00001583 std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001584 std::vector<const PatternToMatch*> > PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001585 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001586 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001587 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner9783d622008-08-26 07:01:28 +00001588 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Chris Lattner706d2d32006-08-09 16:44:44 +00001589 }
1590
Owen Anderson825b72b2009-08-11 20:47:22 +00001591 for (std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001592 std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001593 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1594 ++II) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001595 MVT::SimpleValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001596 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman0540e172008-10-15 06:17:21 +00001597 typedef std::pair<unsigned, std::string> CodeLine;
1598 typedef std::vector<CodeLine> CodeList;
1599 typedef CodeList::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001600
Chris Lattner60d81392008-01-05 22:30:17 +00001601 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001602 std::vector<std::vector<std::string> > PatternOpcodes;
1603 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001604 std::vector<std::set<std::string> > PatternDecls;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001605 std::vector<bool> OutputIsVariadicFlags;
1606 std::vector<unsigned> NumInputRootOpsCounts;
Chris Lattner706d2d32006-08-09 16:44:44 +00001607 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1608 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001609 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001610 std::vector<std::string> TargetOpcodes;
1611 std::vector<std::string> TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001612 bool OutputIsVariadic;
1613 unsigned NumInputRootOps;
Chris Lattner706d2d32006-08-09 16:44:44 +00001614 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001615 TargetOpcodes, TargetVTs,
1616 OutputIsVariadic, NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001617 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1618 PatternDecls.push_back(GeneratedDecl);
1619 PatternOpcodes.push_back(TargetOpcodes);
1620 PatternVTs.push_back(TargetVTs);
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001621 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1622 NumInputRootOpsCounts.push_back(NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001623 }
1624
Chris Lattner706d2d32006-08-09 16:44:44 +00001625 // Factor target node emission code (emitted by EmitResultCode) into
1626 // separate functions. Uniquing and share them among all instruction
1627 // selection routines.
1628 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1629 CodeList &GeneratedCode = CodeForPatterns[i].second;
1630 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1631 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001632 std::set<std::string> Decls = PatternDecls[i];
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001633 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1634 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001635 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001636 int CodeSize = (int)GeneratedCode.size();
1637 int LastPred = -1;
1638 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001639 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001640 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001641 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1642 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001643 }
1644
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001645 std::string CalleeCode = "(SDNode *N";
Evan Cheng9ade2182006-08-26 05:34:46 +00001646 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001647 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1648 CalleeCode += ", unsigned Opc" + utostr(j);
1649 CallerCode += ", " + TargetOpcodes[j];
1650 }
1651 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Anderson69110c92009-09-11 09:01:57 +00001652 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Chris Lattner706d2d32006-08-09 16:44:44 +00001653 CallerCode += ", " + TargetVTs[j];
1654 }
Evan Chengf5493192006-08-26 01:02:19 +00001655 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001656 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001657 std::string Name = *I;
Dan Gohman475871a2008-07-27 21:46:04 +00001658 CalleeCode += ", SDValue &" + Name;
Evan Cheng676d7312006-08-26 00:59:04 +00001659 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001660 }
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001661
1662 if (OutputIsVariadic) {
1663 CalleeCode += ", unsigned NumInputRootOps";
1664 CallerCode += ", " + utostr(NumInputRootOps);
1665 }
1666
Chris Lattner706d2d32006-08-09 16:44:44 +00001667 CallerCode += ");";
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001668 CalleeCode += ") {\n";
Evan Cheng676d7312006-08-26 00:59:04 +00001669
1670 for (std::vector<std::string>::const_reverse_iterator
1671 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1672 CalleeCode += " " + *I + "\n";
1673
Evan Chengf5493192006-08-26 01:02:19 +00001674 for (int j = LastPred+1; j < CodeSize; ++j)
1675 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001676 for (int j = LastPred+1; j < CodeSize; ++j)
1677 GeneratedCode.pop_back();
1678 CalleeCode += "}\n";
1679
1680 // Uniquing the emission routines.
1681 unsigned EmitFuncNum;
1682 std::map<std::string, unsigned>::iterator EFI =
1683 EmitFunctions.find(CalleeCode);
1684 if (EFI != EmitFunctions.end()) {
1685 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001686 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001687 EmitFuncNum = EmitFunctions.size();
1688 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001689 // Prevent emission routines from being inlined to reduce selection
1690 // routines stack frame sizes.
1691 OS << "DISABLE_INLINE ";
Evan Cheng06d64702006-08-11 08:59:35 +00001692 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001693 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001694
Chris Lattner706d2d32006-08-09 16:44:44 +00001695 // Replace the emission code within selection routines with calls to the
1696 // emission functions.
Chris Lattnera0cdf172010-02-13 20:06:50 +00001697 if (GenDebug)
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001698 GeneratedCode.push_back(std::make_pair(0,
1699 "CurDAG->setSubgraphColor(N, \"red\");"));
1700 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) +CallerCode;
David Greene8ad4c002008-10-27 21:56:29 +00001701 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1702 if (GenDebug) {
1703 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001704 GeneratedCode.push_back(std::make_pair(0,
1705 " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1706 GeneratedCode.push_back(std::make_pair(0,
1707 " CurDAG->setSubgraphColor(Result, \"black\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001708 GeneratedCode.push_back(std::make_pair(0, "}"));
David Greene8ad4c002008-10-27 21:56:29 +00001709 }
1710 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001711 }
1712
Chris Lattner706d2d32006-08-09 16:44:44 +00001713 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001714 std::string OpVTStr;
Owen Anderson825b72b2009-08-11 20:47:22 +00001715 if (OpVT == MVT::iPTR) {
Chris Lattner33a40042006-11-14 22:17:10 +00001716 OpVTStr = "_iPTR";
Owen Anderson825b72b2009-08-11 20:47:22 +00001717 } else if (OpVT == MVT::iPTRAny) {
Mon P Wange3b3a722008-07-30 04:36:53 +00001718 OpVTStr = "_iPTRAny";
Owen Anderson825b72b2009-08-11 20:47:22 +00001719 } else if (OpVT == MVT::isVoid) {
Chris Lattner33a40042006-11-14 22:17:10 +00001720 // Nodes with a void result actually have a first result type of either
1721 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1722 // void to this case, we handle it specially here.
1723 } else {
Owen Anderson825b72b2009-08-11 20:47:22 +00001724 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Chris Lattner33a40042006-11-14 22:17:10 +00001725 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001726 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1727 OpcodeVTMap.find(OpName);
1728 if (OpVTI == OpcodeVTMap.end()) {
1729 std::vector<std::string> VTSet;
1730 VTSet.push_back(OpVTStr);
1731 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1732 } else
1733 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001734
Dan Gohman0540e172008-10-15 06:17:21 +00001735 // We want to emit all of the matching code now. However, we want to emit
1736 // the matches in order of minimal cost. Sort the patterns so the least
1737 // cost one is at the start.
1738 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1739 PatternSortingPredicate(CGP));
1740
1741 // Scan the code to see if all of the patterns are reachable and if it is
1742 // possible that the last one might not match.
1743 bool mightNotMatch = true;
1744 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1745 CodeList &GeneratedCode = CodeForPatterns[i].second;
1746 mightNotMatch = false;
1747
1748 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1749 if (GeneratedCode[j].first == 1) { // predicate.
1750 mightNotMatch = true;
1751 break;
1752 }
1753 }
1754
1755 // If this pattern definitely matches, and if it isn't the last one, the
1756 // patterns after it CANNOT ever match. Error out.
1757 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001758 errs() << "Pattern '";
1759 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1760 errs() << "' is impossible to select!\n";
Dan Gohman0540e172008-10-15 06:17:21 +00001761 exit(1);
1762 }
1763 }
1764
Chris Lattner706d2d32006-08-09 16:44:44 +00001765 // Loop through and reverse all of the CodeList vectors, as we will be
1766 // accessing them from their logical front, but accessing the end of a
1767 // vector is more efficient.
1768 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1769 CodeList &GeneratedCode = CodeForPatterns[i].second;
1770 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001771 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001772
1773 // Next, reverse the list of patterns itself for the same reason.
1774 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1775
Dan Gohman63e3e632009-01-29 01:37:18 +00001776 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001777 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman63e3e632009-01-29 01:37:18 +00001778
Chris Lattner706d2d32006-08-09 16:44:44 +00001779 // Emit all of the patterns now, grouped together to share code.
1780 EmitPatterns(CodeForPatterns, 2, OS);
1781
Chris Lattner64906972006-09-21 18:28:27 +00001782 // If the last pattern has predicates (which could fail) emit code to
1783 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001784 if (mightNotMatch) {
Dan Gohman31bd42b2008-09-27 23:53:14 +00001785 OS << "\n";
Chris Lattner409ac582010-02-17 06:28:22 +00001786 OS << " CannotYetSelect(N);\n";
Dan Gohman31bd42b2008-09-27 23:53:14 +00001787 OS << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001788 }
1789 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001790 }
Chris Lattner602f6922006-01-04 00:25:00 +00001791 }
1792
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001793 OS << "// The main instruction selector code.\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001794 << "SDNode *SelectCode(SDNode *N) {\n"
1795 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1796 << " switch (N->getOpcode()) {\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001797 << " default:\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001798 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001799 << " break;\n"
1800 << " case ISD::EntryToken: // These nodes remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001801 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001802 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001803 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001804 << " case ISD::TargetConstant:\n"
Nate Begemane1795842008-02-14 08:57:00 +00001805 << " case ISD::TargetConstantFP:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001806 << " case ISD::TargetConstantPool:\n"
1807 << " case ISD::TargetFrameIndex:\n"
Bill Wendling056292f2008-09-16 21:48:12 +00001808 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman8c2b5252009-10-30 01:27:03 +00001809 << " case ISD::TargetBlockAddress:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001810 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001811 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohman8be6bbe2008-11-05 04:14:16 +00001812 << " case ISD::TargetGlobalAddress:\n"
1813 << " case ISD::TokenFactor:\n"
1814 << " case ISD::CopyFromReg:\n"
1815 << " case ISD::CopyToReg: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001816 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001817 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001818 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001819 << " case ISD::AssertZext: {\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001820 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001821 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001822 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001823 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohmancd920d92008-07-02 23:23:19 +00001824 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Chengda47e6e2008-03-15 00:03:38 +00001825 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001826
Chris Lattner602f6922006-01-04 00:25:00 +00001827 // Loop over all of the case statements, emiting a call to each method we
1828 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001829 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001830 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1831 PBOI != E; ++PBOI) {
1832 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001833 // Potentially multiple versions of select for this opcode. One for each
1834 // ValueType of the node (or its first true operand if it doesn't produce a
1835 // result.
1836 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1837 OpcodeVTMap.find(OpName);
1838 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001839 OS << " case " << OpName << ": {\n";
Dale Johannesen3b895cf2009-05-12 22:32:29 +00001840 // If we have only one variant and it's the default, elide the
1841 // switch. Marginally faster, and makes MSVC happier.
1842 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1843 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1844 OS << " break;\n";
1845 OS << " }\n";
1846 continue;
1847 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001848 // Keep track of whether we see a pattern that has an iPtr result.
1849 bool HasPtrPattern = false;
1850 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001851
Evan Cheng425e8c72007-09-04 20:18:28 +00001852 OS << " switch (NVT) {\n";
1853 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1854 std::string &VTStr = OpVTs[i];
1855 if (VTStr.empty()) {
1856 HasDefaultPattern = true;
1857 continue;
1858 }
Chris Lattner717a6112006-11-14 21:50:27 +00001859
Evan Cheng425e8c72007-09-04 20:18:28 +00001860 // If this is a match on iPTR: don't emit it directly, we need special
1861 // code.
1862 if (VTStr == "_iPTR") {
1863 HasPtrPattern = true;
1864 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00001865 }
Owen Anderson825b72b2009-08-11 20:47:22 +00001866 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng425e8c72007-09-04 20:18:28 +00001867 << " return Select_" << getLegalCName(OpName)
1868 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001869 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001870 OS << " default:\n";
1871
1872 // If there is an iPTR result version of this pattern, emit it here.
1873 if (HasPtrPattern) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001874 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00001875 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1876 }
1877 if (HasDefaultPattern) {
1878 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1879 }
1880 OS << " break;\n";
1881 OS << " }\n";
1882 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001883 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00001884 }
Chris Lattner81303322005-09-23 19:36:15 +00001885
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001886 OS << " } // end of big switch.\n\n"
Chris Lattner409ac582010-02-17 06:28:22 +00001887 << " CannotYetSelect(N);\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00001888 << " return NULL;\n"
1889 << "}\n\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001890}
1891
Daniel Dunbar1a551802009-07-03 00:10:29 +00001892void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001893 EmitSourceFileHeader("DAG Instruction Selector for the " +
1894 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001895
Chris Lattner1f39e292005-09-14 00:09:24 +00001896 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1897 << "// *** instruction selector class. These functions are really "
1898 << "methods.\n\n";
Chris Lattnerf8dc0612008-02-03 06:49:24 +00001899
Roman Levenstein6422e8a2008-05-14 10:17:11 +00001900 OS << "// Include standard, target-independent definitions and methods used\n"
1901 << "// by the instruction selector.\n";
Mike Stumpfe095f32009-05-04 18:40:41 +00001902 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00001903
Chris Lattner443e3f92008-01-05 22:54:53 +00001904 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00001905 EmitPredicateFunctions(OS);
1906
Chris Lattner569f1212009-08-23 04:44:11 +00001907 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerfe718932008-01-06 01:10:31 +00001908 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00001909 I != E; ++I) {
Chris Lattner569f1212009-08-23 04:44:11 +00001910 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1911 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1912 DEBUG(errs() << "\n");
Bill Wendlingf5da1332006-12-07 22:21:48 +00001913 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001914
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001915 // At this point, we have full information about the 'Patterns' we need to
1916 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001917 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001918 EmitInstructionSelector(OS);
1919
Chris Lattner0ab1c5f2010-02-21 06:03:56 +00001920#if 0
Chris Lattnerda272d12010-02-15 08:04:42 +00001921 MatcherNode *Matcher = 0;
1922 // Walk the patterns backwards, building a matcher for each and adding it to
1923 // the matcher for the whole target.
1924 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1925 E = CGP.ptm_end(); I != E;) {
1926 const PatternToMatch &Pattern = *--E;
1927 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
1928
1929 if (Matcher == 0)
1930 Matcher = N;
1931 else
1932 Matcher = new PushMatcherNode(N, Matcher);
1933 }
Chris Lattner05446e72010-02-16 23:13:59 +00001934
1935 // OptimizeMatcher(Matcher);
Chris Lattnerda272d12010-02-15 08:04:42 +00001936 EmitMatcherTable(Matcher, OS);
Chris Lattnerda272d12010-02-15 08:04:42 +00001937 //Matcher->dump();
1938 delete Matcher;
1939#endif
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001940}