blob: 32556729d1f9b8ae0e3045f400c8db2249608d28 [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.
172static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000173 bool FoundRC = false;
Owen Anderson825b72b2009-08-11 20:47:22 +0000174 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000175 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
176 std::vector<CodeGenRegisterClass>::const_iterator RC;
177 std::vector<Record*>::const_iterator Element;
178
179 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
180 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
181 if (Element != (*RC).Elements.end()) {
182 if (!FoundRC) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000183 FoundRC = true;
Jim Grosbach54f30222009-03-25 23:28:33 +0000184 VT = (*RC).getValueTypeNum(0);
185 } else {
186 // In multiple RC's
187 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000188 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach54f30222009-03-25 23:28:33 +0000189 // target is responsible for handling this.
Owen Anderson825b72b2009-08-11 20:47:22 +0000190 return MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000191 }
192 }
193 }
194 }
195 return VT;
Evan Cheng66a48bb2005-12-01 00:18:45 +0000196}
197
Evan Chengf9d03182008-07-03 08:39:51 +0000198static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
199 return CGP.getSDNodeInfo(Op).getEnumName();
200}
201
Chris Lattnerdc32f982008-01-05 22:43:57 +0000202//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000203// Node Transformation emitter implementation.
204//
Daniel Dunbar1a551802009-07-03 00:10:29 +0000205void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner443e3f92008-01-05 22:54:53 +0000206 // Walk the pattern fragments, adding them to a map, which sorts them by
207 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000208 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000209 NXsByNameTy NXsByName;
210
Chris Lattnerfe718932008-01-06 01:10:31 +0000211 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000212 I != E; ++I)
213 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
214
215 OS << "\n// Node transformations.\n";
216
217 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
218 I != E; ++I) {
219 Record *SDNode = I->second.first;
220 std::string Code = I->second.second;
221
222 if (Code.empty()) continue; // Empty code? Skip it.
223
Chris Lattner200c57e2008-01-05 22:58:54 +0000224 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000225 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
226
Dan Gohman475871a2008-07-27 21:46:04 +0000227 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner443e3f92008-01-05 22:54:53 +0000228 << ") {\n";
229 if (ClassName != "SDNode")
230 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
231 OS << Code << "\n}\n";
232 }
233}
234
235//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000236// Predicate emitter implementation.
237//
238
Daniel Dunbar1a551802009-07-03 00:10:29 +0000239void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattnerdc32f982008-01-05 22:43:57 +0000240 OS << "\n// Predicate functions.\n";
241
242 // Walk the pattern fragments, adding them to a map, which sorts them by
243 // name.
244 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
245 PFsByNameTy PFsByName;
246
Chris Lattnerfe718932008-01-06 01:10:31 +0000247 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000248 I != E; ++I)
249 PFsByName.insert(std::make_pair(I->first->getName(), *I));
250
251
252 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
253 I != E; ++I) {
254 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
255 TreePattern *P = I->second.second;
256
257 // If there is a code init for this fragment, emit the predicate code.
258 std::string Code = PatFragRecord->getValueAsCode("Predicate");
259 if (Code.empty()) continue;
260
261 if (P->getOnlyTree()->isLeaf())
262 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattnerccba15f2010-02-16 07:26:36 +0000263 << "(SDNode *N) const {\n";
Chris Lattnerdc32f982008-01-05 22:43:57 +0000264 else {
265 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000266 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000267 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
268
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattnerccba15f2010-02-16 07:26:36 +0000270 << "(SDNode *" << C2 << ") const {\n";
Chris Lattnerdc32f982008-01-05 22:43:57 +0000271 if (ClassName != "SDNode")
272 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
273 }
274 OS << Code << "\n}\n";
275 }
276
277 OS << "\n\n";
278}
279
280
281//===----------------------------------------------------------------------===//
282// PatternCodeEmitter implementation.
283//
Evan Chengb915f312005-12-09 22:45:35 +0000284class PatternCodeEmitter {
285private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000286 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000287
Evan Cheng58e84a62005-12-14 22:02:59 +0000288 // Predicates.
Dan Gohman22bb3112008-08-22 00:20:26 +0000289 std::string PredicateCheck;
Evan Cheng59413202006-04-19 18:07:24 +0000290 // Pattern cost.
291 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000292 // Instruction selector pattern.
293 TreePatternNode *Pattern;
294 // Matched instruction.
295 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000296
Evan Chengb915f312005-12-09 22:45:35 +0000297 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000298 std::map<std::string, std::string> VariableMap;
299 // Node to operator mapping
300 std::map<std::string, Record*> OperatorMap;
Evan Chenga58891f2008-02-05 22:50:29 +0000301 // Name of the folded node which produces a flag.
302 std::pair<std::string, unsigned> FoldedFlag;
Evan Chengb915f312005-12-09 22:45:35 +0000303 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000304 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000305 // Original input chain(s).
306 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000307 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000308
Dan Gohman69de1932008-02-06 22:27:42 +0000309 /// LSI - Load/Store information.
310 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
311 /// for each memory access. This facilitates the use of AliasAnalysis in
312 /// the backend.
313 std::vector<std::string> LSI;
314
Evan Cheng676d7312006-08-26 00:59:04 +0000315 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000316 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000317 /// tested, and if true, the match fails) [when 1], or normal code to emit
318 /// [when 0], or initialization code to emit [when 2].
319 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman475871a2008-07-27 21:46:04 +0000320 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Evan Cheng21ad3922006-02-07 00:37:41 +0000321 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000322 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000323 /// TargetOpcodes - The target specific opcodes used by the resulting
324 /// instructions.
325 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000326 std::vector<std::string> &TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000327 /// OutputIsVariadic - Records whether the instruction output pattern uses
328 /// variable_ops. This requires that the Emit function be passed an
329 /// additional argument to indicate where the input varargs operands
330 /// begin.
331 bool &OutputIsVariadic;
332 /// NumInputRootOps - Records the number of operands the root node of the
333 /// input pattern has. This information is used in the generated code to
334 /// pass to Emit functions when variable_ops processing is needed.
335 unsigned &NumInputRootOps;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000336
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000337 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000338 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000339 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000340 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000341
342 void emitCheck(const std::string &S) {
343 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000344 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000345 }
346 void emitCode(const std::string &S) {
347 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000348 GeneratedCode.push_back(std::make_pair(0, S));
349 }
350 void emitInit(const std::string &S) {
351 if (!S.empty())
352 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000353 }
Evan Chengf5493192006-08-26 01:02:19 +0000354 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000355 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000356 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000357 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000358 void emitOpcode(const std::string &Opc) {
359 TargetOpcodes.push_back(Opc);
360 OpcNo++;
361 }
Evan Chengf8729402006-07-16 06:12:52 +0000362 void emitVT(const std::string &VT) {
363 TargetVTs.push_back(VT);
364 VTNo++;
365 }
Evan Chengb915f312005-12-09 22:45:35 +0000366public:
Dan Gohman22bb3112008-08-22 00:20:26 +0000367 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Evan Cheng58e84a62005-12-14 22:02:59 +0000368 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000369 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000370 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000371 std::vector<std::string> &to,
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000372 std::vector<std::string> &tv,
373 bool &oiv,
374 unsigned &niro)
Dan Gohman22bb3112008-08-22 00:20:26 +0000375 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000376 GeneratedCode(gc), GeneratedDecl(gd),
377 TargetOpcodes(to), TargetVTs(tv),
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000378 OutputIsVariadic(oiv), NumInputRootOps(niro),
Chris Lattner706d2d32006-08-09 16:44:44 +0000379 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000380
381 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
382 /// if the match fails. At this point, we already know that the opcode for N
383 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000384 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
385 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000386 bool &FoundChain);
Chris Lattner39e73f72006-10-11 04:05:55 +0000387
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000388 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb85356242008-01-31 07:27:46 +0000389 const std::string &RootName,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000390 const std::string &ChainSuffix, bool &FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000391
392 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
393 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000394 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000395 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000396 bool InFlagDecled, bool ResNodeDecled,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000397 bool LikeLeaf = false, bool isRoot = false);
Evan Chengb915f312005-12-09 22:45:35 +0000398
Chris Lattner488580c2006-01-28 19:06:51 +0000399 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
400 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +0000401 /// 'Pat' may be missing types. If we find an unresolved type to add a check
402 /// for, this returns true otherwise false if Pat has all types.
403 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +0000404 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +0000405 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +0000406 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +0000407 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +0000408 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +0000409 // The top level node type is checked outside of the select function.
410 if (!isRoot)
Anton Korobeynikovc2fd9192009-11-08 12:14:54 +0000411 emitCheck(Prefix + ".getValueType() == " +
Chris Lattner706d2d32006-08-09 16:44:44 +0000412 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +0000413 return true;
Evan Chengb915f312005-12-09 22:45:35 +0000414 }
415
Chris Lattner47661322010-02-14 22:22:58 +0000416 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000417 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
418 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
419 Prefix + utostr(OpNo)))
420 return true;
421 return false;
422 }
423
424private:
Evan Cheng54597732006-01-26 00:22:25 +0000425 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +0000426 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +0000427 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +0000428 bool &ChainEmitted, bool &InFlagDecled,
429 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000430 const CodeGenTarget &T = CGP.getTargetInfo();
Chris Lattner47661322010-02-14 22:22:58 +0000431 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
432 bool HasInFlag = N->NodeHasProperty(SDNPInFlag, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000433 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
434 TreePatternNode *Child = N->getChild(i);
435 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000436 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
437 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +0000438 } else {
439 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +0000440 if (!Child->getName().empty()) {
441 std::string Name = RootName + utostr(OpNo);
442 if (Duplicates.find(Name) != Duplicates.end())
443 // A duplicate! Do not emit a copy for this node.
444 continue;
445 }
446
Evan Chengb915f312005-12-09 22:45:35 +0000447 Record *RR = DI->getDef();
448 if (RR->isSubClassOf("Register")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000449 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
450 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000451 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000452 emitCode("SDValue InFlag = " +
453 getValueName(RootName + utostr(OpNo)) + ";");
Evan Cheng676d7312006-08-26 00:59:04 +0000454 InFlagDecled = true;
455 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000456 emitCode("InFlag = " +
457 getValueName(RootName + utostr(OpNo)) + ";");
Evan Chengb2c6d492006-01-11 22:16:13 +0000458 } else {
459 if (!ChainEmitted) {
Dan Gohman475871a2008-07-27 21:46:04 +0000460 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000461 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +0000462 ChainEmitted = true;
463 }
Evan Cheng676d7312006-08-26 00:59:04 +0000464 if (!InFlagDecled) {
Dan Gohman475871a2008-07-27 21:46:04 +0000465 emitCode("SDValue InFlag(0, 0);");
Evan Cheng676d7312006-08-26 00:59:04 +0000466 InFlagDecled = true;
467 }
Dale Johannesen874ae252009-06-02 03:12:52 +0000468 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
469 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000470 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000471 ", " + getQualifiedName(RR) +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000472 ", " + getValueName(RootName + utostr(OpNo)) +
473 ", InFlag).getNode();");
Dale Johannesen874ae252009-06-02 03:12:52 +0000474 ResNodeDecled = true;
Dan Gohman475871a2008-07-27 21:46:04 +0000475 emitCode(ChainName + " = SDValue(ResNode, 0);");
476 emitCode("InFlag = SDValue(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +0000477 }
478 }
479 }
480 }
481 }
Evan Cheng54597732006-01-26 00:22:25 +0000482
Dale Johannesen874ae252009-06-02 03:12:52 +0000483 if (HasInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000484 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000485 emitCode("SDValue InFlag = " + getNodeName(RootName) +
486 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000487 InFlagDecled = true;
488 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000489 emitCode("InFlag = " + getNodeName(RootName) +
490 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000491 }
Evan Chengb915f312005-12-09 22:45:35 +0000492 }
493};
494
Chris Lattnera0cdf172010-02-13 20:06:50 +0000495
496/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
497/// if the match fails. At this point, we already know that the opcode for N
498/// matches, and the SDNode for the result has the RootName specified name.
499void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
500 const std::string &RootName,
501 const std::string &ChainSuffix,
502 bool &FoundChain) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000503 // Save loads/stores matched by a pattern.
504 if (!N->isLeaf() && N->getName().empty()) {
Chris Lattner47661322010-02-14 22:22:58 +0000505 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattnera0cdf172010-02-13 20:06:50 +0000506 LSI.push_back(getNodeName(RootName));
507 }
508
509 bool isRoot = (P == NULL);
510 // Emit instruction predicates. Each predicate is just a string for now.
511 if (isRoot) {
512 // Record input varargs info.
513 NumInputRootOps = N->getNumChildren();
Chris Lattnera0cdf172010-02-13 20:06:50 +0000514 emitCheck(PredicateCheck);
515 }
516
517 if (N->isLeaf()) {
518 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
519 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
520 ")->getSExtValue() == INT64_C(" +
521 itostr(II->getValue()) + ")");
522 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000523 }
Chris Lattner05446e72010-02-16 23:13:59 +0000524 assert(N->getComplexPatternInfo(CGP) != 0 &&
525 "Cannot match this as a leaf value!");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000526 }
527
528 // If this node has a name associated with it, capture it in VariableMap. If
529 // we already saw this in the pattern, emit code to verify dagness.
530 if (!N->getName().empty()) {
531 std::string &VarMapEntry = VariableMap[N->getName()];
532 if (VarMapEntry.empty()) {
533 VarMapEntry = RootName;
534 } else {
535 // If we get here, this is a second reference to a specific name. Since
536 // we already have checked that the first reference is valid, we don't
537 // have to recursively match it, just check that it's the same as the
538 // previously named thing.
539 emitCheck(VarMapEntry + " == " + RootName);
540 return;
541 }
542
543 if (!N->isLeaf())
544 OperatorMap[N->getName()] = N->getOperator();
545 }
546
547
548 // Emit code to load the child nodes and match their contents recursively.
549 unsigned OpNo = 0;
Chris Lattner47661322010-02-14 22:22:58 +0000550 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
551 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000552 if (HasChain) {
553 if (NodeHasChain)
554 OpNo = 1;
555 if (!isRoot) {
Evan Cheng014bf212010-02-15 19:41:07 +0000556 // Check if it's profitable to fold the node. e.g. Check for multiple uses
557 // of actual result?
558 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner29c62702010-02-16 19:03:34 +0000559 if (!NodeHasChain) {
560 // If this is just an interior node, check to see if it has a single
561 // use. If the node has multiple uses and the pattern has a load as
562 // an operand, then we can't fold the load.
563 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattner92d3ada2010-02-16 22:35:06 +0000564 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000565 // If the immediate use can somehow reach this node through another
566 // path, then can't fold it either or it will create a cycle.
567 // e.g. In the following diagram, XX can reach ld through YY. If
568 // ld is folded into XX, then YY is both a predecessor and a successor
569 // of XX.
570 //
571 // [ld]
572 // ^ ^
573 // | |
574 // / \---
575 // / [YY]
576 // | ^
577 // [XX]-------|
Chris Lattnere39650a2010-02-16 06:10:58 +0000578
579 // We know we need the check if N's parent is not the root.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000580 bool NeedCheck = P != Pattern;
581 if (!NeedCheck) {
Chris Lattner29c62702010-02-16 19:03:34 +0000582 // If the parent is the root and the node has more than one operand,
583 // we need to check.
Chris Lattnera0cdf172010-02-13 20:06:50 +0000584 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
585 NeedCheck =
586 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
587 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
588 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
589 PInfo.getNumOperands() > 1 ||
590 PInfo.hasProperty(SDNPHasChain) ||
591 PInfo.hasProperty(SDNPInFlag) ||
592 PInfo.hasProperty(SDNPOptInFlag);
593 }
594
595 if (NeedCheck) {
Chris Lattner29c62702010-02-16 19:03:34 +0000596 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
597 ", " + getNodeName(ParentName) + ", N)");
Evan Cheng014bf212010-02-15 19:41:07 +0000598 emitCheck("IsLegalToFold(" + getValueName(RootName) +
Chris Lattnera0cdf172010-02-13 20:06:50 +0000599 ", " + getNodeName(ParentName) + ", N)");
Chris Lattner29c62702010-02-16 19:03:34 +0000600 } else {
601 // Otherwise, just verify that the node only has a single use.
602 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000603 }
604 }
605 }
606
607 if (NodeHasChain) {
608 if (FoundChain) {
Chris Lattnerd9c1a342010-02-17 05:35:28 +0000609 emitCheck("IsChainCompatible(" + ChainName + ".getNode(), " +
610 getNodeName(RootName) + ")");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000611 OrigChains.push_back(std::make_pair(ChainName,
612 getValueName(RootName)));
613 } else
614 FoundChain = true;
615 ChainName = "Chain" + ChainSuffix;
Chris Lattner92d3ada2010-02-16 22:35:06 +0000616
617 if (!N->getComplexPatternInfo(CGP) ||
618 isRoot)
619 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
620 "->getOperand(0);");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000621 }
622 }
623
Chris Lattnera0cdf172010-02-13 20:06:50 +0000624 // If there are node predicates for this, emit the calls.
625 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
626 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
627
628 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
629 // a constant without a predicate fn that has more that one bit set, handle
630 // this as a special case. This is usually for targets that have special
631 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
632 // handling stuff). Using these instructions is often far more efficient
633 // than materializing the constant. Unfortunately, both the instcombiner
634 // and the dag combiner can often infer that bits are dead, and thus drop
635 // them from the mask in the dag. For example, it might turn 'AND X, 255'
636 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
637 // to handle this.
638 if (!N->isLeaf() &&
639 (N->getOperator()->getName() == "and" ||
640 N->getOperator()->getName() == "or") &&
641 N->getChild(1)->isLeaf() &&
642 N->getChild(1)->getPredicateFns().empty()) {
643 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
644 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
645 emitInit("SDValue " + RootName + "0" + " = " +
646 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
647 emitInit("SDValue " + RootName + "1" + " = " +
648 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
649
650 unsigned NTmp = TmpNo++;
651 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
652 " = dyn_cast<ConstantSDNode>(" +
653 getNodeName(RootName + "1") + ");");
654 emitCheck("Tmp" + utostr(NTmp));
655 const char *MaskPredicate = N->getOperator()->getName() == "or"
656 ? "CheckOrMask(" : "CheckAndMask(";
657 emitCheck(MaskPredicate + getValueName(RootName + "0") +
658 ", Tmp" + utostr(NTmp) +
659 ", INT64_C(" + itostr(II->getValue()) + "))");
660
661 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
662 ChainSuffix + utostr(0), FoundChain);
663 return;
664 }
665 }
666 }
667
668 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
669 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
670 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
671
672 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
673 ChainSuffix + utostr(OpNo), FoundChain);
674 }
675
676 // Handle cases when root is a complex pattern.
677 const ComplexPattern *CP;
Chris Lattner92d3ada2010-02-16 22:35:06 +0000678 if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000679 std::string Fn = CP->getSelectFunc();
680 unsigned NumOps = CP->getNumOperands();
681 for (unsigned i = 0; i < NumOps; ++i) {
682 emitDecl("CPTmp" + RootName + "_" + utostr(i));
683 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
684 }
685 if (CP->hasProperty(SDNPHasChain)) {
686 emitDecl("CPInChain");
687 emitDecl("Chain" + ChainSuffix);
688 emitCode("SDValue CPInChain;");
689 emitCode("SDValue Chain" + ChainSuffix + ";");
690 }
691
Chris Lattner92d3ada2010-02-16 22:35:06 +0000692 std::string Code = Fn + "(N, "; // always pass in the root.
693 Code += getValueName(RootName);
Chris Lattnera0cdf172010-02-13 20:06:50 +0000694 for (unsigned i = 0; i < NumOps; i++)
695 Code += ", CPTmp" + RootName + "_" + utostr(i);
696 if (CP->hasProperty(SDNPHasChain)) {
697 ChainName = "Chain" + ChainSuffix;
Chris Lattnere609a512010-02-17 00:31:50 +0000698 Code += ", CPInChain, " + ChainName;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000699 }
700 emitCheck(Code + ")");
701 }
702}
703
704void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
705 TreePatternNode *Parent,
706 const std::string &RootName,
707 const std::string &ChainSuffix,
708 bool &FoundChain) {
709 if (!Child->isLeaf()) {
710 // If it's not a leaf, recursively match.
711 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
712 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
713 CInfo.getEnumName());
714 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
715 bool HasChain = false;
Chris Lattner47661322010-02-14 22:22:58 +0000716 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000717 HasChain = true;
718 FoldedChains.push_back(std::make_pair(getValueName(RootName),
719 CInfo.getNumResults()));
720 }
Chris Lattner47661322010-02-14 22:22:58 +0000721 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
Chris Lattnera0cdf172010-02-13 20:06:50 +0000722 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
723 "Pattern folded multiple nodes which produce flags?");
724 FoldedFlag = std::make_pair(getValueName(RootName),
725 CInfo.getNumResults() + (unsigned)HasChain);
726 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000727 return;
728 }
729
730 if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
Chris Lattner92d3ada2010-02-16 22:35:06 +0000731 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
732 bool HasChain = false;
733
734 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
735 HasChain = true;
736 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
737 FoldedChains.push_back(std::make_pair("CPInChain",
738 PInfo.getNumResults()));
739 }
740 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
741 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
742 "Pattern folded multiple nodes which produce flags?");
743 FoldedFlag = std::make_pair(getValueName(RootName),
744 CP->getNumOperands() + (unsigned)HasChain);
745 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000746 return;
747 }
748
749 // If this child has a name associated with it, capture it in VarMap. If
750 // we already saw this in the pattern, emit code to verify dagness.
751 if (!Child->getName().empty()) {
752 std::string &VarMapEntry = VariableMap[Child->getName()];
753 if (VarMapEntry.empty()) {
754 VarMapEntry = getValueName(RootName);
755 } else {
756 // If we get here, this is a second reference to a specific name.
757 // Since we already have checked that the first reference is valid,
758 // we don't have to recursively match it, just check that it's the
759 // same as the previously named thing.
760 emitCheck(VarMapEntry + " == " + getValueName(RootName));
761 Duplicates.insert(getValueName(RootName));
762 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000763 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000764 }
765
766 // Handle leaves of various types.
767 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
768 Record *LeafRec = DI->getDef();
769 if (LeafRec->isSubClassOf("RegisterClass") ||
770 LeafRec->isSubClassOf("PointerLikeRegClass")) {
771 // Handle register references. Nothing to do here.
772 } else if (LeafRec->isSubClassOf("Register")) {
773 // Handle register references.
774 } else if (LeafRec->getName() == "srcvalue") {
775 // Place holder for SRCVALUE nodes. Nothing to do here.
776 } else if (LeafRec->isSubClassOf("ValueType")) {
777 // Make sure this is the specified value type.
778 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
779 ")->getVT() == MVT::" + LeafRec->getName());
780 } else if (LeafRec->isSubClassOf("CondCode")) {
781 // Make sure this is the specified cond code.
782 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
783 ")->get() == ISD::" + LeafRec->getName());
Chris Lattnera0cdf172010-02-13 20:06:50 +0000784 } else {
785#ifndef NDEBUG
786 Child->dump();
Chris Lattner5b08f772010-02-16 22:38:31 +0000787 errs() << " ";
Chris Lattnera0cdf172010-02-13 20:06:50 +0000788#endif
789 assert(0 && "Unknown leaf type!");
790 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000791
792 // If there are node predicates for this, emit the calls.
793 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
794 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
795 ")");
796 return;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000797 }
Chris Lattner5b08f772010-02-16 22:38:31 +0000798
799 if (IntInit *II = dynamic_cast<IntInit*>(Child->getLeafValue())) {
800 unsigned NTmp = TmpNo++;
801 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
802 " = dyn_cast<ConstantSDNode>("+
803 getNodeName(RootName) + ");");
804 emitCheck("Tmp" + utostr(NTmp));
805 unsigned CTmp = TmpNo++;
806 emitCode("int64_t CN"+ utostr(CTmp) +
807 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
808 emitCheck("CN" + utostr(CTmp) + " == "
809 "INT64_C(" +itostr(II->getValue()) + ")");
810 return;
811 }
812#ifndef NDEBUG
813 Child->dump();
814#endif
815 assert(0 && "Unknown leaf type!");
Chris Lattnera0cdf172010-02-13 20:06:50 +0000816}
817
818/// EmitResultCode - Emit the action for a pattern. Now that it has matched
819/// we actually have to build a DAG!
820std::vector<std::string>
821PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
822 std::vector<Record*> DstRegs,
823 bool InFlagDecled, bool ResNodeDecled,
824 bool LikeLeaf, bool isRoot) {
825 // List of arguments of getMachineNode() or SelectNodeTo().
826 std::vector<std::string> NodeOps;
827 // This is something selected from the pattern we matched.
828 if (!N->getName().empty()) {
829 const std::string &VarName = N->getName();
830 std::string Val = VariableMap[VarName];
831 bool ModifiedVal = false;
832 if (Val.empty()) {
833 errs() << "Variable '" << VarName << " referenced but not defined "
834 << "and not caught earlier!\n";
835 abort();
836 }
837 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
838 // Already selected this operand, just return the tmpval.
839 NodeOps.push_back(getValueName(Val));
840 return NodeOps;
841 }
842
843 const ComplexPattern *CP;
844 unsigned ResNo = TmpNo++;
845 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
846 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
847 std::string CastType;
848 std::string TmpVar = "Tmp" + utostr(ResNo);
849 switch (N->getTypeNum(0)) {
850 default:
851 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
852 << " type as an immediate constant. Aborting\n";
853 abort();
854 case MVT::i1: CastType = "bool"; break;
855 case MVT::i8: CastType = "unsigned char"; break;
856 case MVT::i16: CastType = "unsigned short"; break;
857 case MVT::i32: CastType = "unsigned"; break;
858 case MVT::i64: CastType = "uint64_t"; break;
859 }
860 emitCode("SDValue " + TmpVar +
861 " = CurDAG->getTargetConstant(((" + CastType +
862 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
863 getEnumName(N->getTypeNum(0)) + ");");
864 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
865 // value if used multiple times by this pattern result.
866 Val = TmpVar;
867 ModifiedVal = true;
868 NodeOps.push_back(getValueName(Val));
869 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
870 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
871 std::string TmpVar = "Tmp" + utostr(ResNo);
872 emitCode("SDValue " + TmpVar +
873 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
874 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
875 Val + ")->getValueType(0));");
876 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
877 // value if used multiple times by this pattern result.
878 Val = TmpVar;
879 ModifiedVal = true;
880 NodeOps.push_back(getValueName(Val));
881 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
882 Record *Op = OperatorMap[N->getName()];
883 // Transform ExternalSymbol to TargetExternalSymbol
884 if (Op && Op->getName() == "externalsym") {
885 std::string TmpVar = "Tmp"+utostr(ResNo);
886 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
887 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
888 Val + ")->getSymbol(), " +
889 getEnumName(N->getTypeNum(0)) + ");");
890 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
891 // this value if used multiple times by this pattern result.
892 Val = TmpVar;
893 ModifiedVal = true;
894 }
895 NodeOps.push_back(getValueName(Val));
896 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
897 || N->getOperator()->getName() == "tglobaltlsaddr")) {
898 Record *Op = OperatorMap[N->getName()];
899 // Transform GlobalAddress to TargetGlobalAddress
900 if (Op && (Op->getName() == "globaladdr" ||
901 Op->getName() == "globaltlsaddr")) {
902 std::string TmpVar = "Tmp" + utostr(ResNo);
903 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
904 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
905 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
906 ");");
907 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
908 // this value if used multiple times by this pattern result.
909 Val = TmpVar;
910 ModifiedVal = true;
911 }
912 NodeOps.push_back(getValueName(Val));
913 } else if (!N->isLeaf()
Chris Lattner47661322010-02-14 22:22:58 +0000914 && (N->getOperator()->getName() == "texternalsym" ||
915 N->getOperator()->getName() == "tconstpool")) {
916 // Do not rewrite the variable name, since we don't generate a new
917 // temporary.
918 NodeOps.push_back(getValueName(Val));
919 } else if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
920 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
921 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
922 }
923 } else {
924 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
925 // node even if it isn't one. Don't select it.
926 if (!LikeLeaf) {
927 if (isRoot && N->isLeaf()) {
928 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
929 emitCode("return NULL;");
930 }
931 }
932 NodeOps.push_back(getValueName(Val));
Chris Lattnera0cdf172010-02-13 20:06:50 +0000933 }
Chris Lattner47661322010-02-14 22:22:58 +0000934
935 if (ModifiedVal)
936 VariableMap[VarName] = Val;
Chris Lattnera0cdf172010-02-13 20:06:50 +0000937 return NodeOps;
938 }
939 if (N->isLeaf()) {
940 // If this is an explicit register reference, handle it.
941 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
942 unsigned ResNo = TmpNo++;
943 if (DI->getDef()->isSubClassOf("Register")) {
944 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
945 getQualifiedName(DI->getDef()) + ", " +
946 getEnumName(N->getTypeNum(0)) + ");");
947 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
948 return NodeOps;
949 } else if (DI->getDef()->getName() == "zero_reg") {
950 emitCode("SDValue Tmp" + utostr(ResNo) +
951 " = CurDAG->getRegister(0, " +
952 getEnumName(N->getTypeNum(0)) + ");");
953 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
954 return NodeOps;
955 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
956 // Handle a reference to a register class. This is used
957 // in COPY_TO_SUBREG instructions.
958 emitCode("SDValue Tmp" + utostr(ResNo) +
959 " = CurDAG->getTargetConstant(" +
960 getQualifiedName(DI->getDef()) + "RegClassID, " +
961 "MVT::i32);");
962 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
963 return NodeOps;
964 }
965 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
966 unsigned ResNo = TmpNo++;
967 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
968 emitCode("SDValue Tmp" + utostr(ResNo) +
969 " = CurDAG->getTargetConstant(0x" +
970 utohexstr((uint64_t) II->getValue()) +
971 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
972 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
973 return NodeOps;
974 }
975
976#ifndef NDEBUG
977 N->dump();
978#endif
979 assert(0 && "Unknown leaf type!");
980 return NodeOps;
981 }
982
983 Record *Op = N->getOperator();
984 if (Op->isSubClassOf("Instruction")) {
985 const CodeGenTarget &CGT = CGP.getTargetInfo();
986 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
987 const DAGInstruction &Inst = CGP.getInstruction(Op);
988 const TreePattern *InstPat = Inst.getPattern();
989 // FIXME: Assume actual pattern comes before "implicit".
990 TreePatternNode *InstPatNode =
991 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
992 : (InstPat ? InstPat->getTree(0) : NULL);
993 if (InstPatNode && !InstPatNode->isLeaf() &&
994 InstPatNode->getOperator()->getName() == "set") {
995 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
996 }
997 bool IsVariadic = isRoot && II.isVariadic;
998 // FIXME: fix how we deal with physical register operands.
999 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1000 bool HasImpResults = isRoot && DstRegs.size() > 0;
1001 bool NodeHasOptInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +00001002 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001003 bool NodeHasInFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +00001004 Pattern->TreeHasProperty(SDNPInFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001005 bool NodeHasOutFlag = isRoot &&
Chris Lattner47661322010-02-14 22:22:58 +00001006 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001007 bool NodeHasChain = InstPatNode &&
Chris Lattner47661322010-02-14 22:22:58 +00001008 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
1009 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
Chris Lattnera0cdf172010-02-13 20:06:50 +00001010 unsigned NumResults = Inst.getNumResults();
1011 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1012
1013 // Record output varargs info.
1014 OutputIsVariadic = IsVariadic;
1015
1016 if (NodeHasOptInFlag) {
1017 emitCode("bool HasInFlag = "
1018 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1019 "MVT::Flag);");
1020 }
1021 if (IsVariadic)
1022 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1023
1024 // How many results is this pattern expected to produce?
1025 unsigned NumPatResults = 0;
1026 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1027 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1028 if (VT != MVT::isVoid && VT != MVT::Flag)
1029 NumPatResults++;
1030 }
1031
1032 if (OrigChains.size() > 0) {
1033 // The original input chain is being ignored. If it is not just
1034 // pointing to the op that's being folded, we should create a
1035 // TokenFactor with it and the chain of the folded op as the new chain.
1036 // We could potentially be doing multiple levels of folding, in that
1037 // case, the TokenFactor can have more operands.
1038 emitCode("SmallVector<SDValue, 8> InChains;");
1039 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1040 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1041 OrigChains[i].second + ".getNode()) {");
1042 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1043 emitCode("}");
1044 }
1045 emitCode("InChains.push_back(" + ChainName + ");");
1046 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1047 "N->getDebugLoc(), MVT::Other, "
1048 "&InChains[0], InChains.size());");
1049 if (GenDebug) {
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001050 emitCode("CurDAG->setSubgraphColor(" + ChainName +
1051 ".getNode(), \"yellow\");");
1052 emitCode("CurDAG->setSubgraphColor(" + ChainName +
1053 ".getNode(), \"black\");");
Chris Lattnera0cdf172010-02-13 20:06:50 +00001054 }
1055 }
1056
1057 // Loop over all of the operands of the instruction pattern, emitting code
1058 // to fill them all in. The node 'N' usually has number children equal to
1059 // the number of input operands of the instruction. However, in cases
1060 // where there are predicate operands for an instruction, we need to fill
1061 // in the 'execute always' values. Match up the node operands to the
1062 // instruction operands to do this.
1063 std::vector<std::string> AllOps;
1064 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1065 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1066 std::vector<std::string> Ops;
1067
1068 // Determine what to emit for this operand.
1069 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1070 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1071 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1072 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1073 // This is a predicate or optional def operand; emit the
1074 // 'default ops' operands.
1075 const DAGDefaultOperand &DefaultOp =
1076 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1077 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1078 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1079 InFlagDecled, ResNodeDecled);
1080 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1081 }
1082 } else {
1083 // Otherwise this is a normal operand or a predicate operand without
1084 // 'execute always'; emit it.
1085 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1086 InFlagDecled, ResNodeDecled);
1087 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1088 ++ChildNo;
1089 }
1090 }
1091
1092 // Emit all the chain and CopyToReg stuff.
1093 bool ChainEmitted = NodeHasChain;
1094 if (NodeHasInFlag || HasImpInputs)
1095 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1096 InFlagDecled, ResNodeDecled, true);
1097 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1098 if (!InFlagDecled) {
1099 emitCode("SDValue InFlag(0, 0);");
1100 InFlagDecled = true;
1101 }
1102 if (NodeHasOptInFlag) {
1103 emitCode("if (HasInFlag) {");
1104 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1105 emitCode("}");
1106 }
1107 }
1108
1109 unsigned ResNo = TmpNo++;
1110
1111 unsigned OpsNo = OpcNo;
1112 std::string CodePrefix;
1113 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1114 std::deque<std::string> After;
1115 std::string NodeName;
1116 if (!isRoot) {
1117 NodeName = "Tmp" + utostr(ResNo);
1118 CodePrefix = "SDValue " + NodeName + "(";
1119 } else {
1120 NodeName = "ResNode";
1121 if (!ResNodeDecled) {
1122 CodePrefix = "SDNode *" + NodeName + " = ";
1123 ResNodeDecled = true;
1124 } else
1125 CodePrefix = NodeName + " = ";
1126 }
1127
1128 std::string Code = "Opc" + utostr(OpcNo);
1129
1130 if (!isRoot || (InputHasChain && !NodeHasChain))
1131 // For call to "getMachineNode()".
1132 Code += ", N->getDebugLoc()";
1133
1134 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1135
1136 // Output order: results, chain, flags
1137 // Result types.
1138 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1139 Code += ", VT" + utostr(VTNo);
1140 emitVT(getEnumName(N->getTypeNum(0)));
1141 }
1142 // Add types for implicit results in physical registers, scheduler will
1143 // care of adding copyfromreg nodes.
1144 for (unsigned i = 0; i < NumDstRegs; i++) {
1145 Record *RR = DstRegs[i];
1146 if (RR->isSubClassOf("Register")) {
1147 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1148 Code += ", " + getEnumName(RVT);
1149 }
1150 }
1151 if (NodeHasChain)
1152 Code += ", MVT::Other";
1153 if (NodeHasOutFlag)
1154 Code += ", MVT::Flag";
1155
1156 // Inputs.
1157 if (IsVariadic) {
1158 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1159 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1160 AllOps.clear();
1161
1162 // Figure out whether any operands at the end of the op list are not
1163 // part of the variable section.
1164 std::string EndAdjust;
1165 if (NodeHasInFlag || HasImpInputs)
1166 EndAdjust = "-1"; // Always has one flag.
1167 else if (NodeHasOptInFlag)
1168 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1169
1170 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1171 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1172
1173 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1174 emitCode("}");
1175 }
1176
1177 // Populate MemRefs with entries for each memory accesses covered by
1178 // this pattern.
1179 if (isRoot && !LSI.empty()) {
1180 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1181 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1182 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1183 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1184 emitCode(MemRefs + "[" + utostr(i) + "] = "
1185 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1186 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1187 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1188 ");");
1189 }
1190
1191 if (NodeHasChain) {
1192 if (IsVariadic)
1193 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1194 else
1195 AllOps.push_back(ChainName);
1196 }
1197
1198 if (IsVariadic) {
1199 if (NodeHasInFlag || HasImpInputs)
1200 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1201 else if (NodeHasOptInFlag) {
1202 emitCode("if (HasInFlag)");
1203 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1204 }
1205 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1206 ".size()";
1207 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1208 AllOps.push_back("InFlag");
1209
1210 unsigned NumOps = AllOps.size();
1211 if (NumOps) {
1212 if (!NodeHasOptInFlag && NumOps < 4) {
1213 for (unsigned i = 0; i != NumOps; ++i)
1214 Code += ", " + AllOps[i];
1215 } else {
1216 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1217 for (unsigned i = 0; i != NumOps; ++i) {
1218 OpsCode += AllOps[i];
1219 if (i != NumOps-1)
1220 OpsCode += ", ";
1221 }
1222 emitCode(OpsCode + " };");
1223 Code += ", Ops" + utostr(OpsNo) + ", ";
1224 if (NodeHasOptInFlag) {
1225 Code += "HasInFlag ? ";
1226 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1227 } else
1228 Code += utostr(NumOps);
1229 }
1230 }
1231
1232 if (!isRoot)
1233 Code += "), 0";
1234
1235 std::vector<std::string> ReplaceFroms;
1236 std::vector<std::string> ReplaceTos;
1237 if (!isRoot) {
1238 NodeOps.push_back("Tmp" + utostr(ResNo));
1239 } else {
1240
1241 if (NodeHasOutFlag) {
1242 if (!InFlagDecled) {
1243 After.push_back("SDValue InFlag(ResNode, " +
1244 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1245 ");");
1246 InFlagDecled = true;
1247 } else
1248 After.push_back("InFlag = SDValue(ResNode, " +
1249 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1250 ");");
1251 }
1252
1253 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1254 ReplaceFroms.push_back("SDValue(" +
1255 FoldedChains[j].first + ".getNode(), " +
1256 utostr(FoldedChains[j].second) +
1257 ")");
1258 ReplaceTos.push_back("SDValue(ResNode, " +
1259 utostr(NumResults+NumDstRegs) + ")");
1260 }
1261
1262 if (NodeHasOutFlag) {
1263 if (FoldedFlag.first != "") {
1264 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1265 utostr(FoldedFlag.second) + ")");
1266 ReplaceTos.push_back("InFlag");
1267 } else {
Chris Lattner47661322010-02-14 22:22:58 +00001268 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
Chris Lattnera0cdf172010-02-13 20:06:50 +00001269 ReplaceFroms.push_back("SDValue(N, " +
1270 utostr(NumPatResults + (unsigned)InputHasChain)
1271 + ")");
1272 ReplaceTos.push_back("InFlag");
1273 }
1274 }
1275
1276 if (!ReplaceFroms.empty() && InputHasChain) {
1277 ReplaceFroms.push_back("SDValue(N, " +
1278 utostr(NumPatResults) + ")");
1279 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1280 ChainName + ".getResNo()" + ")");
1281 ChainAssignmentNeeded |= NodeHasChain;
1282 }
1283
1284 // User does not expect the instruction would produce a chain!
1285 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1286 ;
1287 } else if (InputHasChain && !NodeHasChain) {
1288 // One of the inner node produces a chain.
1289 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1290 ReplaceFroms.push_back("SDValue(N, " +
1291 utostr(NumPatResults) + ")");
1292 ReplaceTos.push_back(ChainName);
1293 }
1294 }
1295
1296 if (ChainAssignmentNeeded) {
1297 // Remember which op produces the chain.
1298 std::string ChainAssign;
1299 if (!isRoot)
1300 ChainAssign = ChainName + " = SDValue(" + NodeName +
1301 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1302 else
1303 ChainAssign = ChainName + " = SDValue(" + NodeName +
1304 ", " + utostr(NumResults+NumDstRegs) + ");";
1305
1306 After.push_front(ChainAssign);
1307 }
1308
1309 if (ReplaceFroms.size() == 1) {
1310 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1311 ReplaceTos[0] + ");");
1312 } else if (!ReplaceFroms.empty()) {
1313 After.push_back("const SDValue Froms[] = {");
1314 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1315 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1316 After.push_back("};");
1317 After.push_back("const SDValue Tos[] = {");
1318 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1319 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1320 After.push_back("};");
1321 After.push_back("ReplaceUses(Froms, Tos, " +
1322 itostr(ReplaceFroms.size()) + ");");
1323 }
1324
1325 // We prefer to use SelectNodeTo since it avoids allocation when
1326 // possible and it avoids CSE map recalculation for the node's
1327 // users, however it's tricky to use in a non-root context.
1328 //
1329 // We also don't use SelectNodeTo if the pattern replacement is being
1330 // used to jettison a chain result, since morphing the node in place
1331 // would leave users of the chain dangling.
1332 //
1333 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1334 Code = "CurDAG->getMachineNode(" + Code;
1335 } else {
1336 Code = "CurDAG->SelectNodeTo(N, " + Code;
1337 }
1338 if (isRoot) {
1339 if (After.empty())
1340 CodePrefix = "return ";
1341 else
1342 After.push_back("return ResNode;");
1343 }
1344
1345 emitCode(CodePrefix + Code + ");");
1346
1347 if (GenDebug) {
1348 if (!isRoot) {
1349 emitCode("CurDAG->setSubgraphColor(" +
1350 NodeName +".getNode(), \"yellow\");");
1351 emitCode("CurDAG->setSubgraphColor(" +
1352 NodeName +".getNode(), \"black\");");
1353 } else {
1354 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1355 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1356 }
1357 }
1358
1359 for (unsigned i = 0, e = After.size(); i != e; ++i)
1360 emitCode(After[i]);
1361
1362 return NodeOps;
1363 }
1364 if (Op->isSubClassOf("SDNodeXForm")) {
1365 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1366 // PatLeaf node - the operand may or may not be a leaf node. But it should
1367 // behave like one.
1368 std::vector<std::string> Ops =
1369 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1370 ResNodeDecled, true);
1371 unsigned ResNo = TmpNo++;
1372 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1373 + "(" + Ops.back() + ".getNode());");
1374 NodeOps.push_back("Tmp" + utostr(ResNo));
1375 if (isRoot)
1376 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1377 return NodeOps;
1378 }
1379
1380 N->dump();
1381 errs() << "\n";
1382 throw std::string("Unknown node in result pattern!");
1383}
1384
1385
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001386/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1387/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001388/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001389void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001390 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001391 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001392 std::vector<std::string> &TargetOpcodes,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001393 std::vector<std::string> &TargetVTs,
1394 bool &OutputIsVariadic,
1395 unsigned &NumInputRootOps) {
1396 OutputIsVariadic = false;
1397 NumInputRootOps = 0;
1398
Dan Gohman22bb3112008-08-22 00:20:26 +00001399 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001400 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001401 GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001402 TargetOpcodes, TargetVTs,
1403 OutputIsVariadic, NumInputRootOps);
Evan Chengb915f312005-12-09 22:45:35 +00001404
Chris Lattner8fc35682005-09-23 23:16:51 +00001405 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001406 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001407 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001408
Chris Lattnerc87bf382010-02-14 21:11:53 +00001409 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1410 // diagnostics, which we know are impossible at this point.
Chris Lattner200c57e2008-01-05 22:58:54 +00001411 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001412
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001413 // At this point, we know that we structurally match the pattern, but the
1414 // types of the nodes may not match. Figure out the fewest number of type
1415 // comparisons we need to emit. For example, if there is only one integer
1416 // type supported by a target, there should be no type comparisons at all for
1417 // integer patterns!
1418 //
1419 // To figure out the fewest number of type checks needed, clone the pattern,
1420 // remove the types, then perform type inference on the pattern as a whole.
1421 // If there are unresolved types, emit an explicit check for those types,
1422 // apply the type to the tree, then rerun type inference. Iterate until all
1423 // types are resolved.
1424 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001425 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner47661322010-02-14 22:22:58 +00001426 Pat->RemoveAllTypes();
Chris Lattner7e82f132005-10-15 21:34:21 +00001427
1428 do {
1429 // Resolve/propagate as many types as possible.
1430 try {
1431 bool MadeChange = true;
1432 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001433 MadeChange = Pat->ApplyTypeConstraints(TP,
1434 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001435 } catch (...) {
1436 assert(0 && "Error: could not find consistent types for something we"
1437 " already decided was ok!");
1438 abort();
1439 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001440
Chris Lattner7e82f132005-10-15 21:34:21 +00001441 // Insert a check for an unresolved type and add it to the tree. If we find
1442 // an unresolved type to add a check for, this returns true and we iterate,
1443 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001444 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001445
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001446 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001447 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001448 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001449}
1450
Chris Lattner24e00a42006-01-29 04:41:05 +00001451/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1452/// a line causes any of them to be empty, remove them and return true when
1453/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001454static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001455 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001456 &Patterns) {
1457 bool ErasedPatterns = false;
1458 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1459 Patterns[i].second.pop_back();
1460 if (Patterns[i].second.empty()) {
1461 Patterns.erase(Patterns.begin()+i);
1462 --i; --e;
1463 ErasedPatterns = true;
1464 }
1465 }
1466 return ErasedPatterns;
1467}
1468
Chris Lattner8bc74722006-01-29 04:25:26 +00001469/// EmitPatterns - Emit code for at least one pattern, but try to group common
1470/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001471void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001472 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001473 &Patterns, unsigned Indent,
Daniel Dunbar1a551802009-07-03 00:10:29 +00001474 raw_ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001475 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001476 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001477 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001478
1479 if (Patterns.empty()) return;
1480
Chris Lattner24e00a42006-01-29 04:41:05 +00001481 // Figure out how many patterns share the next code line. Explicitly copy
1482 // FirstCodeLine so that we don't invalidate a reference when changing
1483 // Patterns.
1484 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001485 unsigned LastMatch = Patterns.size()-1;
1486 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1487 --LastMatch;
1488
1489 // If not all patterns share this line, split the list into two pieces. The
1490 // first chunk will use this line, the second chunk won't.
1491 if (LastMatch != 0) {
1492 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1493 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1494
1495 // FIXME: Emit braces?
1496 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001497 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001498 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1499 Pattern.getSrcPattern()->print(OS);
1500 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1501 Pattern.getDstPattern()->print(OS);
1502 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001503 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001504 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001505 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001506 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001507 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001508 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001509 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001510 }
Evan Cheng676d7312006-08-26 00:59:04 +00001511 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001512 OS << std::string(Indent, ' ') << "{\n";
1513 Indent += 2;
1514 }
1515 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001516 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001517 Indent -= 2;
1518 OS << std::string(Indent, ' ') << "}\n";
1519 }
1520
1521 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001522 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001523 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1524 Pattern.getSrcPattern()->print(OS);
1525 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1526 Pattern.getDstPattern()->print(OS);
1527 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001528 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001529 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001530 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001531 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001532 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001533 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001534 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001535 }
1536 EmitPatterns(Other, Indent, OS);
1537 return;
1538 }
1539
Chris Lattner24e00a42006-01-29 04:41:05 +00001540 // Remove this code from all of the patterns that share it.
1541 bool ErasedPatterns = EraseCodeLine(Patterns);
1542
Evan Cheng676d7312006-08-26 00:59:04 +00001543 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001544
1545 // Otherwise, every pattern in the list has this line. Emit it.
1546 if (!isPredicate) {
1547 // Normal code.
1548 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1549 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001550 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1551
1552 // If the next code line is another predicate, and if all of the pattern
1553 // in this group share the same next line, emit it inline now. Do this
1554 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001555 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00001556 // Check that all of the patterns in Patterns end with the same predicate.
Chris Lattner24e00a42006-01-29 04:41:05 +00001557 bool AllEndWithSamePredicate = true;
1558 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1559 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1560 AllEndWithSamePredicate = false;
1561 break;
1562 }
1563 // If all of the predicates aren't the same, we can't share them.
1564 if (!AllEndWithSamePredicate) break;
1565
1566 // Otherwise we can. Emit it shared now.
1567 OS << " &&\n" << std::string(Indent+4, ' ')
1568 << Patterns.back().second.back().second;
1569 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001570 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001571
1572 OS << ") {\n";
1573 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001574 }
1575
1576 EmitPatterns(Patterns, Indent, OS);
1577
1578 if (isPredicate)
1579 OS << std::string(Indent-2, ' ') << "}\n";
1580}
1581
Evan Cheng892aaf82006-11-08 23:01:03 +00001582static std::string getLegalCName(std::string OpName) {
1583 std::string::size_type pos = OpName.find("::");
1584 if (pos != std::string::npos)
1585 OpName.replace(pos, 2, "_");
1586 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001587}
1588
Daniel Dunbar1a551802009-07-03 00:10:29 +00001589void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001590 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattnerda272d12010-02-15 08:04:42 +00001591
Dan Gohman1e0ee4b2008-08-20 21:45:57 +00001592 // Get the namespace to insert instructions into.
1593 std::string InstNS = Target.getInstNamespace();
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001594 if (!InstNS.empty()) InstNS += "::";
1595
Chris Lattner602f6922006-01-04 00:25:00 +00001596 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001597 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001598 // All unique target node emission functions.
1599 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001600 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001601 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001602 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001603 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001604 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001605 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001606 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001607 } else {
1608 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001609 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001610 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001611 push_back(&Pattern);
Chris Lattner47661322010-02-14 22:22:58 +00001612 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001613 std::vector<Record*> OpNodes = CP->getRootNodes();
1614 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001615 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1616 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001617 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001618 }
1619 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001620 errs() << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001621 Node->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001622 errs() << "' on tree pattern '";
1623 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001624 exit(1);
1625 }
1626 }
1627 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001628
1629 // For each opcode, there might be multiple select functions, one per
1630 // ValueType of the node (or its first operand if it doesn't produce a
1631 // non-chain result.
1632 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1633
Chris Lattner602f6922006-01-04 00:25:00 +00001634 // Emit one Select_* method for each top-level opcode. We do this instead of
1635 // emitting one giant switch statement to support compilers where this will
1636 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001637 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001638 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1639 PBOI != E; ++PBOI) {
1640 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001641 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001642 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1643
Chris Lattner706d2d32006-08-09 16:44:44 +00001644 // Split them into groups by type.
Owen Anderson825b72b2009-08-11 20:47:22 +00001645 std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001646 std::vector<const PatternToMatch*> > PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001647 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001648 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001649 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner9783d622008-08-26 07:01:28 +00001650 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Chris Lattner706d2d32006-08-09 16:44:44 +00001651 }
1652
Owen Anderson825b72b2009-08-11 20:47:22 +00001653 for (std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001654 std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001655 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1656 ++II) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001657 MVT::SimpleValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001658 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman0540e172008-10-15 06:17:21 +00001659 typedef std::pair<unsigned, std::string> CodeLine;
1660 typedef std::vector<CodeLine> CodeList;
1661 typedef CodeList::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001662
Chris Lattner60d81392008-01-05 22:30:17 +00001663 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001664 std::vector<std::vector<std::string> > PatternOpcodes;
1665 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001666 std::vector<std::set<std::string> > PatternDecls;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001667 std::vector<bool> OutputIsVariadicFlags;
1668 std::vector<unsigned> NumInputRootOpsCounts;
Chris Lattner706d2d32006-08-09 16:44:44 +00001669 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1670 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001671 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001672 std::vector<std::string> TargetOpcodes;
1673 std::vector<std::string> TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001674 bool OutputIsVariadic;
1675 unsigned NumInputRootOps;
Chris Lattner706d2d32006-08-09 16:44:44 +00001676 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001677 TargetOpcodes, TargetVTs,
1678 OutputIsVariadic, NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001679 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1680 PatternDecls.push_back(GeneratedDecl);
1681 PatternOpcodes.push_back(TargetOpcodes);
1682 PatternVTs.push_back(TargetVTs);
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001683 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1684 NumInputRootOpsCounts.push_back(NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001685 }
1686
Chris Lattner706d2d32006-08-09 16:44:44 +00001687 // Factor target node emission code (emitted by EmitResultCode) into
1688 // separate functions. Uniquing and share them among all instruction
1689 // selection routines.
1690 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1691 CodeList &GeneratedCode = CodeForPatterns[i].second;
1692 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1693 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001694 std::set<std::string> Decls = PatternDecls[i];
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001695 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1696 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001697 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001698 int CodeSize = (int)GeneratedCode.size();
1699 int LastPred = -1;
1700 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001701 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001702 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001703 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1704 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001705 }
1706
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001707 std::string CalleeCode = "(SDNode *N";
Evan Cheng9ade2182006-08-26 05:34:46 +00001708 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001709 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1710 CalleeCode += ", unsigned Opc" + utostr(j);
1711 CallerCode += ", " + TargetOpcodes[j];
1712 }
1713 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Anderson69110c92009-09-11 09:01:57 +00001714 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Chris Lattner706d2d32006-08-09 16:44:44 +00001715 CallerCode += ", " + TargetVTs[j];
1716 }
Evan Chengf5493192006-08-26 01:02:19 +00001717 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001718 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001719 std::string Name = *I;
Dan Gohman475871a2008-07-27 21:46:04 +00001720 CalleeCode += ", SDValue &" + Name;
Evan Cheng676d7312006-08-26 00:59:04 +00001721 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001722 }
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001723
1724 if (OutputIsVariadic) {
1725 CalleeCode += ", unsigned NumInputRootOps";
1726 CallerCode += ", " + utostr(NumInputRootOps);
1727 }
1728
Chris Lattner706d2d32006-08-09 16:44:44 +00001729 CallerCode += ");";
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001730 CalleeCode += ") {\n";
Evan Cheng676d7312006-08-26 00:59:04 +00001731
1732 for (std::vector<std::string>::const_reverse_iterator
1733 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1734 CalleeCode += " " + *I + "\n";
1735
Evan Chengf5493192006-08-26 01:02:19 +00001736 for (int j = LastPred+1; j < CodeSize; ++j)
1737 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001738 for (int j = LastPred+1; j < CodeSize; ++j)
1739 GeneratedCode.pop_back();
1740 CalleeCode += "}\n";
1741
1742 // Uniquing the emission routines.
1743 unsigned EmitFuncNum;
1744 std::map<std::string, unsigned>::iterator EFI =
1745 EmitFunctions.find(CalleeCode);
1746 if (EFI != EmitFunctions.end()) {
1747 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001748 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001749 EmitFuncNum = EmitFunctions.size();
1750 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001751 // Prevent emission routines from being inlined to reduce selection
1752 // routines stack frame sizes.
1753 OS << "DISABLE_INLINE ";
Evan Cheng06d64702006-08-11 08:59:35 +00001754 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001755 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001756
Chris Lattner706d2d32006-08-09 16:44:44 +00001757 // Replace the emission code within selection routines with calls to the
1758 // emission functions.
Chris Lattnera0cdf172010-02-13 20:06:50 +00001759 if (GenDebug)
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001760 GeneratedCode.push_back(std::make_pair(0,
1761 "CurDAG->setSubgraphColor(N, \"red\");"));
1762 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) +CallerCode;
David Greene8ad4c002008-10-27 21:56:29 +00001763 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1764 if (GenDebug) {
1765 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
Chris Lattnerdcdcef22010-02-18 00:23:27 +00001766 GeneratedCode.push_back(std::make_pair(0,
1767 " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1768 GeneratedCode.push_back(std::make_pair(0,
1769 " CurDAG->setSubgraphColor(Result, \"black\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001770 GeneratedCode.push_back(std::make_pair(0, "}"));
David Greene8ad4c002008-10-27 21:56:29 +00001771 }
1772 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001773 }
1774
Chris Lattner706d2d32006-08-09 16:44:44 +00001775 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001776 std::string OpVTStr;
Owen Anderson825b72b2009-08-11 20:47:22 +00001777 if (OpVT == MVT::iPTR) {
Chris Lattner33a40042006-11-14 22:17:10 +00001778 OpVTStr = "_iPTR";
Owen Anderson825b72b2009-08-11 20:47:22 +00001779 } else if (OpVT == MVT::iPTRAny) {
Mon P Wange3b3a722008-07-30 04:36:53 +00001780 OpVTStr = "_iPTRAny";
Owen Anderson825b72b2009-08-11 20:47:22 +00001781 } else if (OpVT == MVT::isVoid) {
Chris Lattner33a40042006-11-14 22:17:10 +00001782 // Nodes with a void result actually have a first result type of either
1783 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1784 // void to this case, we handle it specially here.
1785 } else {
Owen Anderson825b72b2009-08-11 20:47:22 +00001786 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Chris Lattner33a40042006-11-14 22:17:10 +00001787 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001788 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1789 OpcodeVTMap.find(OpName);
1790 if (OpVTI == OpcodeVTMap.end()) {
1791 std::vector<std::string> VTSet;
1792 VTSet.push_back(OpVTStr);
1793 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1794 } else
1795 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001796
Dan Gohman0540e172008-10-15 06:17:21 +00001797 // We want to emit all of the matching code now. However, we want to emit
1798 // the matches in order of minimal cost. Sort the patterns so the least
1799 // cost one is at the start.
1800 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1801 PatternSortingPredicate(CGP));
1802
1803 // Scan the code to see if all of the patterns are reachable and if it is
1804 // possible that the last one might not match.
1805 bool mightNotMatch = true;
1806 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1807 CodeList &GeneratedCode = CodeForPatterns[i].second;
1808 mightNotMatch = false;
1809
1810 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1811 if (GeneratedCode[j].first == 1) { // predicate.
1812 mightNotMatch = true;
1813 break;
1814 }
1815 }
1816
1817 // If this pattern definitely matches, and if it isn't the last one, the
1818 // patterns after it CANNOT ever match. Error out.
1819 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001820 errs() << "Pattern '";
1821 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1822 errs() << "' is impossible to select!\n";
Dan Gohman0540e172008-10-15 06:17:21 +00001823 exit(1);
1824 }
1825 }
1826
Chris Lattner706d2d32006-08-09 16:44:44 +00001827 // Loop through and reverse all of the CodeList vectors, as we will be
1828 // accessing them from their logical front, but accessing the end of a
1829 // vector is more efficient.
1830 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1831 CodeList &GeneratedCode = CodeForPatterns[i].second;
1832 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001833 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001834
1835 // Next, reverse the list of patterns itself for the same reason.
1836 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1837
Dan Gohman63e3e632009-01-29 01:37:18 +00001838 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001839 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman63e3e632009-01-29 01:37:18 +00001840
Chris Lattner706d2d32006-08-09 16:44:44 +00001841 // Emit all of the patterns now, grouped together to share code.
1842 EmitPatterns(CodeForPatterns, 2, OS);
1843
Chris Lattner64906972006-09-21 18:28:27 +00001844 // If the last pattern has predicates (which could fail) emit code to
1845 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001846 if (mightNotMatch) {
Dan Gohman31bd42b2008-09-27 23:53:14 +00001847 OS << "\n";
Chris Lattner409ac582010-02-17 06:28:22 +00001848 OS << " CannotYetSelect(N);\n";
Dan Gohman31bd42b2008-09-27 23:53:14 +00001849 OS << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001850 }
1851 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001852 }
Chris Lattner602f6922006-01-04 00:25:00 +00001853 }
1854
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001855 OS << "// The main instruction selector code.\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001856 << "SDNode *SelectCode(SDNode *N) {\n"
1857 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1858 << " switch (N->getOpcode()) {\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001859 << " default:\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001860 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001861 << " break;\n"
1862 << " case ISD::EntryToken: // These nodes remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001863 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001864 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001865 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001866 << " case ISD::TargetConstant:\n"
Nate Begemane1795842008-02-14 08:57:00 +00001867 << " case ISD::TargetConstantFP:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001868 << " case ISD::TargetConstantPool:\n"
1869 << " case ISD::TargetFrameIndex:\n"
Bill Wendling056292f2008-09-16 21:48:12 +00001870 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman8c2b5252009-10-30 01:27:03 +00001871 << " case ISD::TargetBlockAddress:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001872 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001873 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohman8be6bbe2008-11-05 04:14:16 +00001874 << " case ISD::TargetGlobalAddress:\n"
1875 << " case ISD::TokenFactor:\n"
1876 << " case ISD::CopyFromReg:\n"
1877 << " case ISD::CopyToReg: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001878 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001879 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001880 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001881 << " case ISD::AssertZext: {\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001882 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001883 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001884 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001885 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohmancd920d92008-07-02 23:23:19 +00001886 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Chengda47e6e2008-03-15 00:03:38 +00001887 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001888
Chris Lattner602f6922006-01-04 00:25:00 +00001889 // Loop over all of the case statements, emiting a call to each method we
1890 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001891 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001892 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1893 PBOI != E; ++PBOI) {
1894 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001895 // Potentially multiple versions of select for this opcode. One for each
1896 // ValueType of the node (or its first true operand if it doesn't produce a
1897 // result.
1898 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1899 OpcodeVTMap.find(OpName);
1900 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001901 OS << " case " << OpName << ": {\n";
Dale Johannesen3b895cf2009-05-12 22:32:29 +00001902 // If we have only one variant and it's the default, elide the
1903 // switch. Marginally faster, and makes MSVC happier.
1904 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1905 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1906 OS << " break;\n";
1907 OS << " }\n";
1908 continue;
1909 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001910 // Keep track of whether we see a pattern that has an iPtr result.
1911 bool HasPtrPattern = false;
1912 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001913
Evan Cheng425e8c72007-09-04 20:18:28 +00001914 OS << " switch (NVT) {\n";
1915 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1916 std::string &VTStr = OpVTs[i];
1917 if (VTStr.empty()) {
1918 HasDefaultPattern = true;
1919 continue;
1920 }
Chris Lattner717a6112006-11-14 21:50:27 +00001921
Evan Cheng425e8c72007-09-04 20:18:28 +00001922 // If this is a match on iPTR: don't emit it directly, we need special
1923 // code.
1924 if (VTStr == "_iPTR") {
1925 HasPtrPattern = true;
1926 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00001927 }
Owen Anderson825b72b2009-08-11 20:47:22 +00001928 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng425e8c72007-09-04 20:18:28 +00001929 << " return Select_" << getLegalCName(OpName)
1930 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001931 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001932 OS << " default:\n";
1933
1934 // If there is an iPTR result version of this pattern, emit it here.
1935 if (HasPtrPattern) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00001936 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00001937 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1938 }
1939 if (HasDefaultPattern) {
1940 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1941 }
1942 OS << " break;\n";
1943 OS << " }\n";
1944 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001945 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00001946 }
Chris Lattner81303322005-09-23 19:36:15 +00001947
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001948 OS << " } // end of big switch.\n\n"
Chris Lattner409ac582010-02-17 06:28:22 +00001949 << " CannotYetSelect(N);\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00001950 << " return NULL;\n"
1951 << "}\n\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001952}
1953
Daniel Dunbar1a551802009-07-03 00:10:29 +00001954void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001955 EmitSourceFileHeader("DAG Instruction Selector for the " +
1956 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001957
Chris Lattner1f39e292005-09-14 00:09:24 +00001958 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1959 << "// *** instruction selector class. These functions are really "
1960 << "methods.\n\n";
Chris Lattnerf8dc0612008-02-03 06:49:24 +00001961
Roman Levenstein6422e8a2008-05-14 10:17:11 +00001962 OS << "// Include standard, target-independent definitions and methods used\n"
1963 << "// by the instruction selector.\n";
Mike Stumpfe095f32009-05-04 18:40:41 +00001964 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00001965
Chris Lattner443e3f92008-01-05 22:54:53 +00001966 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00001967 EmitPredicateFunctions(OS);
1968
Chris Lattner569f1212009-08-23 04:44:11 +00001969 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerfe718932008-01-06 01:10:31 +00001970 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00001971 I != E; ++I) {
Chris Lattner569f1212009-08-23 04:44:11 +00001972 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1973 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1974 DEBUG(errs() << "\n");
Bill Wendlingf5da1332006-12-07 22:21:48 +00001975 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00001976
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001977 // At this point, we have full information about the 'Patterns' we need to
1978 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00001979 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001980 EmitInstructionSelector(OS);
1981
Chris Lattner03ddb202010-02-17 19:19:50 +00001982#if 0
Chris Lattnerda272d12010-02-15 08:04:42 +00001983 MatcherNode *Matcher = 0;
1984 // Walk the patterns backwards, building a matcher for each and adding it to
1985 // the matcher for the whole target.
1986 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
1987 E = CGP.ptm_end(); I != E;) {
1988 const PatternToMatch &Pattern = *--E;
1989 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
1990
1991 if (Matcher == 0)
1992 Matcher = N;
1993 else
1994 Matcher = new PushMatcherNode(N, Matcher);
1995 }
Chris Lattner05446e72010-02-16 23:13:59 +00001996
1997 // OptimizeMatcher(Matcher);
Chris Lattnerda272d12010-02-15 08:04:42 +00001998 EmitMatcherTable(Matcher, OS);
Chris Lattnerda272d12010-02-15 08:04:42 +00001999 //Matcher->dump();
2000 delete Matcher;
2001#endif
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002002}