blob: 6281b89a93777dbc81aa957d7387477854aef20a [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"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000017#include "llvm/Support/CommandLine.h"
Chris Lattner54cb8fd2005-09-07 23:44:43 +000018#include "llvm/Support/Debug.h"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000019#include "llvm/Support/MathExtras.h"
David Greene8ad4c002008-10-27 21:56:29 +000020#include "llvm/Support/Debug.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000021#include <algorithm>
Dan Gohman95d11092008-07-07 21:00:17 +000022#include <deque>
Daniel Dunbar1a551802009-07-03 00:10:29 +000023#include <iostream>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000024using namespace llvm;
25
Chris Lattner3d4ad292009-08-07 22:27:19 +000026static cl::opt<bool>
27GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
David Greene8ad4c002008-10-27 21:56:29 +000028
Chris Lattnerca559d02005-09-08 21:03:01 +000029//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +000030// DAGISelEmitter Helper methods
Chris Lattner54cb8fd2005-09-07 23:44:43 +000031//
32
Dan Gohmaneeb3a002010-01-05 01:24:18 +000033/// getNodeName - The top level Select_* functions have an "SDNode* N"
34/// argument. When expanding the pattern-matching code, the intermediate
35/// variables have type SDValue. This function provides a uniform way to
36/// reference the underlying "SDNode *" for both cases.
37static std::string getNodeName(const std::string &S) {
38 if (S == "N") return S;
39 return S + ".getNode()";
40}
41
42/// getNodeValue - Similar to getNodeName, except it provides a uniform
43/// way to access the SDValue for both cases.
44static std::string getValueName(const std::string &S) {
45 if (S == "N") return "SDValue(N, 0)";
46 return S;
47}
48
Chris Lattner6cefb772008-01-05 22:25:12 +000049/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
50/// ComplexPattern.
51static bool NodeIsComplexPattern(TreePatternNode *N) {
Evan Cheng0fc71982005-12-08 02:00:36 +000052 return (N->isLeaf() &&
53 dynamic_cast<DefInit*>(N->getLeafValue()) &&
54 static_cast<DefInit*>(N->getLeafValue())->getDef()->
55 isSubClassOf("ComplexPattern"));
56}
57
Chris Lattner6cefb772008-01-05 22:25:12 +000058/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
59/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Evan Cheng0fc71982005-12-08 02:00:36 +000060static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerfe718932008-01-06 01:10:31 +000061 CodeGenDAGPatterns &CGP) {
Evan Cheng0fc71982005-12-08 02:00:36 +000062 if (N->isLeaf() &&
63 dynamic_cast<DefInit*>(N->getLeafValue()) &&
64 static_cast<DefInit*>(N->getLeafValue())->getDef()->
65 isSubClassOf("ComplexPattern")) {
Chris Lattner6cefb772008-01-05 22:25:12 +000066 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
67 ->getDef());
Evan Cheng0fc71982005-12-08 02:00:36 +000068 }
69 return NULL;
70}
71
Chris Lattner05814af2005-09-28 17:57:56 +000072/// getPatternSize - Return the 'size' of this pattern. We want to match large
73/// patterns before small ones. This is used to determine the size of a
74/// pattern.
Chris Lattnerfe718932008-01-06 01:10:31 +000075static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Owen Andersone50ed302009-08-10 22:56:29 +000076 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
77 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Owen Anderson825b72b2009-08-11 20:47:22 +000078 P->getExtTypeNum(0) == MVT::isVoid ||
79 P->getExtTypeNum(0) == MVT::Flag ||
80 P->getExtTypeNum(0) == MVT::iPTR ||
81 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +000082 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +000083 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +000084 // If the root node is a ConstantSDNode, increases its size.
85 // e.g. (set R32:$dst, 0).
86 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000087 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +000088
89 // FIXME: This is a hack to statically increase the priority of patterns
90 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
91 // Later we can allow complexity / cost for each pattern to be (optionally)
92 // specified. To get best possible pattern match we'll need to dynamically
93 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner6cefb772008-01-05 22:25:12 +000094 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000095 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +000096 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +000097
98 // If this node has some predicate function that must match, it adds to the
99 // complexity of this node.
Dan Gohman0540e172008-10-15 06:17:21 +0000100 if (!P->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +0000101 ++Size;
102
Chris Lattner05814af2005-09-28 17:57:56 +0000103 // Count children in the count if they are also nodes.
104 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
105 TreePatternNode *Child = P->getChild(i);
Owen Anderson825b72b2009-08-11 20:47:22 +0000106 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner6cefb772008-01-05 22:25:12 +0000107 Size += getPatternSize(Child, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +0000108 else if (Child->isLeaf()) {
109 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +0000110 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +0000111 else if (NodeIsComplexPattern(Child))
Chris Lattner6cefb772008-01-05 22:25:12 +0000112 Size += getPatternSize(Child, CGP);
Dan Gohman0540e172008-10-15 06:17:21 +0000113 else if (!Child->getPredicateFns().empty())
Chris Lattner3e179802006-02-03 18:06:02 +0000114 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +0000115 }
Chris Lattner05814af2005-09-28 17:57:56 +0000116 }
117
118 return Size;
119}
120
121/// getResultPatternCost - Compute the number of instructions for this pattern.
122/// This is a temporary hack. We should really include the instruction
123/// latencies in this calculation.
Chris Lattner6cefb772008-01-05 22:25:12 +0000124static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000125 CodeGenDAGPatterns &CGP) {
Chris Lattner05814af2005-09-28 17:57:56 +0000126 if (P->isLeaf()) return 0;
127
Evan Chengfbad7082006-02-18 02:33:09 +0000128 unsigned Cost = 0;
129 Record *Op = P->getOperator();
130 if (Op->isSubClassOf("Instruction")) {
131 Cost++;
Chris Lattner6cefb772008-01-05 22:25:12 +0000132 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohman533297b2009-10-29 18:10:34 +0000133 if (II.usesCustomInserter)
Evan Chengfbad7082006-02-18 02:33:09 +0000134 Cost += 10;
135 }
Chris Lattner05814af2005-09-28 17:57:56 +0000136 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000137 Cost += getResultPatternCost(P->getChild(i), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000138 return Cost;
139}
140
Evan Chenge6f32032006-07-19 00:24:41 +0000141/// getResultPatternCodeSize - Compute the code size of instructions for this
142/// pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000143static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000144 CodeGenDAGPatterns &CGP) {
Evan Chenge6f32032006-07-19 00:24:41 +0000145 if (P->isLeaf()) return 0;
146
147 unsigned Cost = 0;
148 Record *Op = P->getOperator();
149 if (Op->isSubClassOf("Instruction")) {
150 Cost += Op->getValueAsInt("CodeSize");
151 }
152 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000153 Cost += getResultPatternSize(P->getChild(i), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000154 return Cost;
155}
156
Chris Lattner05814af2005-09-28 17:57:56 +0000157// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
158// In particular, we want to match maximal patterns first and lowest cost within
159// a particular complexity first.
160struct PatternSortingPredicate {
Chris Lattnerfe718932008-01-06 01:10:31 +0000161 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
162 CodeGenDAGPatterns &CGP;
Evan Cheng0fc71982005-12-08 02:00:36 +0000163
Dan Gohman0540e172008-10-15 06:17:21 +0000164 typedef std::pair<unsigned, std::string> CodeLine;
165 typedef std::vector<CodeLine> CodeList;
166 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
167
168 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
169 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
170 const PatternToMatch *LHS = LHSPair.first;
171 const PatternToMatch *RHS = RHSPair.first;
172
Chris Lattner6cefb772008-01-05 22:25:12 +0000173 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
174 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Evan Chengc81d2a02006-04-19 20:36:09 +0000175 LHSSize += LHS->getAddedComplexity();
176 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +0000177 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
178 if (LHSSize < RHSSize) return false;
179
180 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner6cefb772008-01-05 22:25:12 +0000181 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
182 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000183 if (LHSCost < RHSCost) return true;
184 if (LHSCost > RHSCost) return false;
185
Chris Lattner6cefb772008-01-05 22:25:12 +0000186 return getResultPatternSize(LHS->getDstPattern(), CGP) <
187 getResultPatternSize(RHS->getDstPattern(), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000188 }
189};
190
Jim Grosbach54f30222009-03-25 23:28:33 +0000191/// getRegisterValueType - Look up and return the ValueType of the specified
192/// register. If the register is a member of multiple register classes which
Owen Anderson825b72b2009-08-11 20:47:22 +0000193/// have different associated types, return MVT::Other.
194static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000195 bool FoundRC = false;
Owen Anderson825b72b2009-08-11 20:47:22 +0000196 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000197 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
198 std::vector<CodeGenRegisterClass>::const_iterator RC;
199 std::vector<Record*>::const_iterator Element;
200
201 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
202 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
203 if (Element != (*RC).Elements.end()) {
204 if (!FoundRC) {
Jim Grosbach866cc602009-03-26 14:45:34 +0000205 FoundRC = true;
Jim Grosbach54f30222009-03-25 23:28:33 +0000206 VT = (*RC).getValueTypeNum(0);
207 } else {
208 // In multiple RC's
209 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000210 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach54f30222009-03-25 23:28:33 +0000211 // target is responsible for handling this.
Owen Anderson825b72b2009-08-11 20:47:22 +0000212 return MVT::Other;
Jim Grosbach54f30222009-03-25 23:28:33 +0000213 }
214 }
215 }
216 }
217 return VT;
Evan Cheng66a48bb2005-12-01 00:18:45 +0000218}
219
Chris Lattner72fe91c2005-09-24 00:40:24 +0000220
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000221/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
222/// type information from it.
223static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000224 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000225 if (!N->isLeaf())
226 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
227 RemoveAllTypes(N->getChild(i));
228}
Chris Lattner72fe91c2005-09-24 00:40:24 +0000229
Evan Cheng51fecc82006-01-09 18:27:06 +0000230/// NodeHasProperty - return true if TreePatternNode has the specified
231/// property.
Evan Cheng94b30402006-10-11 21:02:01 +0000232static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerfe718932008-01-06 01:10:31 +0000233 CodeGenDAGPatterns &CGP) {
Evan Cheng94b30402006-10-11 21:02:01 +0000234 if (N->isLeaf()) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000235 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Evan Cheng94b30402006-10-11 21:02:01 +0000236 if (CP)
237 return CP->hasProperty(Property);
238 return false;
239 }
Evan Cheng7b05bd52005-12-23 22:11:47 +0000240 Record *Operator = N->getOperator();
241 if (!Operator->isSubClassOf("SDNode")) return false;
242
Chris Lattner6cefb772008-01-05 22:25:12 +0000243 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +0000244}
245
Evan Cheng94b30402006-10-11 21:02:01 +0000246static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerfe718932008-01-06 01:10:31 +0000247 CodeGenDAGPatterns &CGP) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000248 if (NodeHasProperty(N, Property, CGP))
Evan Cheng7b05bd52005-12-23 22:11:47 +0000249 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +0000250
251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
252 TreePatternNode *Child = N->getChild(i);
Chris Lattner6cefb772008-01-05 22:25:12 +0000253 if (PatternHasProperty(Child, Property, CGP))
Evan Cheng51fecc82006-01-09 18:27:06 +0000254 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +0000255 }
256
257 return false;
258}
259
Evan Chengf9d03182008-07-03 08:39:51 +0000260static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
261 return CGP.getSDNodeInfo(Op).getEnumName();
262}
263
264static
265bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
266 bool isStore = !N->isLeaf() &&
267 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
268 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
269 return false;
270
271 bool HasChain = false;
272 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
273 TreePatternNode *Child = N->getChild(i);
274 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
275 HasChain = true;
276 break;
277 }
278 }
279 return HasChain;
280}
281
Chris Lattnerdc32f982008-01-05 22:43:57 +0000282//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000283// Node Transformation emitter implementation.
284//
Daniel Dunbar1a551802009-07-03 00:10:29 +0000285void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner443e3f92008-01-05 22:54:53 +0000286 // Walk the pattern fragments, adding them to a map, which sorts them by
287 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000288 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000289 NXsByNameTy NXsByName;
290
Chris Lattnerfe718932008-01-06 01:10:31 +0000291 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000292 I != E; ++I)
293 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
294
295 OS << "\n// Node transformations.\n";
296
297 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
298 I != E; ++I) {
299 Record *SDNode = I->second.first;
300 std::string Code = I->second.second;
301
302 if (Code.empty()) continue; // Empty code? Skip it.
303
Chris Lattner200c57e2008-01-05 22:58:54 +0000304 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000305 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
306
Dan Gohman475871a2008-07-27 21:46:04 +0000307 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner443e3f92008-01-05 22:54:53 +0000308 << ") {\n";
309 if (ClassName != "SDNode")
310 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
311 OS << Code << "\n}\n";
312 }
313}
314
315//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000316// Predicate emitter implementation.
317//
318
Daniel Dunbar1a551802009-07-03 00:10:29 +0000319void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattnerdc32f982008-01-05 22:43:57 +0000320 OS << "\n// Predicate functions.\n";
321
322 // Walk the pattern fragments, adding them to a map, which sorts them by
323 // name.
324 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
325 PFsByNameTy PFsByName;
326
Chris Lattnerfe718932008-01-06 01:10:31 +0000327 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000328 I != E; ++I)
329 PFsByName.insert(std::make_pair(I->first->getName(), *I));
330
331
332 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
333 I != E; ++I) {
334 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
335 TreePattern *P = I->second.second;
336
337 // If there is a code init for this fragment, emit the predicate code.
338 std::string Code = PatFragRecord->getValueAsCode("Predicate");
339 if (Code.empty()) continue;
340
341 if (P->getOnlyTree()->isLeaf())
342 OS << "inline bool Predicate_" << PatFragRecord->getName()
343 << "(SDNode *N) {\n";
344 else {
345 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000346 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000347 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
348
349 OS << "inline bool Predicate_" << PatFragRecord->getName()
350 << "(SDNode *" << C2 << ") {\n";
351 if (ClassName != "SDNode")
352 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
353 }
354 OS << Code << "\n}\n";
355 }
356
357 OS << "\n\n";
358}
359
360
361//===----------------------------------------------------------------------===//
362// PatternCodeEmitter implementation.
363//
Evan Chengb915f312005-12-09 22:45:35 +0000364class PatternCodeEmitter {
365private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000366 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000367
Evan Cheng58e84a62005-12-14 22:02:59 +0000368 // Predicates.
Dan Gohman22bb3112008-08-22 00:20:26 +0000369 std::string PredicateCheck;
Evan Cheng59413202006-04-19 18:07:24 +0000370 // Pattern cost.
371 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000372 // Instruction selector pattern.
373 TreePatternNode *Pattern;
374 // Matched instruction.
375 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000376
Evan Chengb915f312005-12-09 22:45:35 +0000377 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000378 std::map<std::string, std::string> VariableMap;
379 // Node to operator mapping
380 std::map<std::string, Record*> OperatorMap;
Evan Chenga58891f2008-02-05 22:50:29 +0000381 // Name of the folded node which produces a flag.
382 std::pair<std::string, unsigned> FoldedFlag;
Evan Chengb915f312005-12-09 22:45:35 +0000383 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000384 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000385 // Original input chain(s).
386 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000387 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000388
Dan Gohman69de1932008-02-06 22:27:42 +0000389 /// LSI - Load/Store information.
390 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
391 /// for each memory access. This facilitates the use of AliasAnalysis in
392 /// the backend.
393 std::vector<std::string> LSI;
394
Evan Cheng676d7312006-08-26 00:59:04 +0000395 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000396 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000397 /// tested, and if true, the match fails) [when 1], or normal code to emit
398 /// [when 0], or initialization code to emit [when 2].
399 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman475871a2008-07-27 21:46:04 +0000400 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Evan Cheng21ad3922006-02-07 00:37:41 +0000401 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000402 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000403 /// TargetOpcodes - The target specific opcodes used by the resulting
404 /// instructions.
405 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000406 std::vector<std::string> &TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000407 /// OutputIsVariadic - Records whether the instruction output pattern uses
408 /// variable_ops. This requires that the Emit function be passed an
409 /// additional argument to indicate where the input varargs operands
410 /// begin.
411 bool &OutputIsVariadic;
412 /// NumInputRootOps - Records the number of operands the root node of the
413 /// input pattern has. This information is used in the generated code to
414 /// pass to Emit functions when variable_ops processing is needed.
415 unsigned &NumInputRootOps;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000416
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000417 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000418 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000419 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000420 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000421
422 void emitCheck(const std::string &S) {
423 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000424 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000425 }
426 void emitCode(const std::string &S) {
427 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000428 GeneratedCode.push_back(std::make_pair(0, S));
429 }
430 void emitInit(const std::string &S) {
431 if (!S.empty())
432 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000433 }
Evan Chengf5493192006-08-26 01:02:19 +0000434 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000435 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000436 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000437 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000438 void emitOpcode(const std::string &Opc) {
439 TargetOpcodes.push_back(Opc);
440 OpcNo++;
441 }
Evan Chengf8729402006-07-16 06:12:52 +0000442 void emitVT(const std::string &VT) {
443 TargetVTs.push_back(VT);
444 VTNo++;
445 }
Evan Chengb915f312005-12-09 22:45:35 +0000446public:
Dan Gohman22bb3112008-08-22 00:20:26 +0000447 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Evan Cheng58e84a62005-12-14 22:02:59 +0000448 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000449 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000450 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000451 std::vector<std::string> &to,
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000452 std::vector<std::string> &tv,
453 bool &oiv,
454 unsigned &niro)
Dan Gohman22bb3112008-08-22 00:20:26 +0000455 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000456 GeneratedCode(gc), GeneratedDecl(gd),
457 TargetOpcodes(to), TargetVTs(tv),
Dan Gohmane4c67cd2008-05-31 02:11:25 +0000458 OutputIsVariadic(oiv), NumInputRootOps(niro),
Chris Lattner706d2d32006-08-09 16:44:44 +0000459 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000460
461 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
462 /// if the match fails. At this point, we already know that the opcode for N
463 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000464 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
465 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000466 bool &FoundChain);
Chris Lattner39e73f72006-10-11 04:05:55 +0000467
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000468 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb85356242008-01-31 07:27:46 +0000469 const std::string &RootName,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000470 const std::string &ChainSuffix, bool &FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000471
472 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
473 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000474 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000475 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000476 bool InFlagDecled, bool ResNodeDecled,
Chris Lattnera0cdf172010-02-13 20:06:50 +0000477 bool LikeLeaf = false, bool isRoot = false);
Evan Chengb915f312005-12-09 22:45:35 +0000478
Chris Lattner488580c2006-01-28 19:06:51 +0000479 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
480 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +0000481 /// 'Pat' may be missing types. If we find an unresolved type to add a check
482 /// for, this returns true otherwise false if Pat has all types.
483 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +0000484 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +0000485 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +0000486 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +0000487 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +0000488 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +0000489 // The top level node type is checked outside of the select function.
490 if (!isRoot)
Anton Korobeynikovc2fd9192009-11-08 12:14:54 +0000491 emitCheck(Prefix + ".getValueType() == " +
Chris Lattner706d2d32006-08-09 16:44:44 +0000492 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +0000493 return true;
Evan Chengb915f312005-12-09 22:45:35 +0000494 }
495
Evan Cheng51fecc82006-01-09 18:27:06 +0000496 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +0000497 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000498 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
499 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
500 Prefix + utostr(OpNo)))
501 return true;
502 return false;
503 }
504
505private:
Evan Cheng54597732006-01-26 00:22:25 +0000506 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +0000507 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +0000508 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +0000509 bool &ChainEmitted, bool &InFlagDecled,
510 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000511 const CodeGenTarget &T = CGP.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +0000512 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +0000513 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
514 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Evan Chengb915f312005-12-09 22:45:35 +0000515 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
516 TreePatternNode *Child = N->getChild(i);
517 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000518 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
519 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +0000520 } else {
521 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +0000522 if (!Child->getName().empty()) {
523 std::string Name = RootName + utostr(OpNo);
524 if (Duplicates.find(Name) != Duplicates.end())
525 // A duplicate! Do not emit a copy for this node.
526 continue;
527 }
528
Evan Chengb915f312005-12-09 22:45:35 +0000529 Record *RR = DI->getDef();
530 if (RR->isSubClassOf("Register")) {
Owen Anderson825b72b2009-08-11 20:47:22 +0000531 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
532 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000533 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000534 emitCode("SDValue InFlag = " +
535 getValueName(RootName + utostr(OpNo)) + ";");
Evan Cheng676d7312006-08-26 00:59:04 +0000536 InFlagDecled = true;
537 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000538 emitCode("InFlag = " +
539 getValueName(RootName + utostr(OpNo)) + ";");
Evan Chengb2c6d492006-01-11 22:16:13 +0000540 } else {
541 if (!ChainEmitted) {
Dan Gohman475871a2008-07-27 21:46:04 +0000542 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000543 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +0000544 ChainEmitted = true;
545 }
Evan Cheng676d7312006-08-26 00:59:04 +0000546 if (!InFlagDecled) {
Dan Gohman475871a2008-07-27 21:46:04 +0000547 emitCode("SDValue InFlag(0, 0);");
Evan Cheng676d7312006-08-26 00:59:04 +0000548 InFlagDecled = true;
549 }
Dale Johannesen874ae252009-06-02 03:12:52 +0000550 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
551 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000552 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000553 ", " + getQualifiedName(RR) +
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000554 ", " + getValueName(RootName + utostr(OpNo)) +
555 ", InFlag).getNode();");
Dale Johannesen874ae252009-06-02 03:12:52 +0000556 ResNodeDecled = true;
Dan Gohman475871a2008-07-27 21:46:04 +0000557 emitCode(ChainName + " = SDValue(ResNode, 0);");
558 emitCode("InFlag = SDValue(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +0000559 }
560 }
561 }
562 }
563 }
Evan Cheng54597732006-01-26 00:22:25 +0000564
Dale Johannesen874ae252009-06-02 03:12:52 +0000565 if (HasInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000566 if (!InFlagDecled) {
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000567 emitCode("SDValue InFlag = " + getNodeName(RootName) +
568 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000569 InFlagDecled = true;
570 } else
Dan Gohmaneeb3a002010-01-05 01:24:18 +0000571 emitCode("InFlag = " + getNodeName(RootName) +
572 "->getOperand(" + utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000573 }
Evan Chengb915f312005-12-09 22:45:35 +0000574 }
575};
576
Chris Lattnera0cdf172010-02-13 20:06:50 +0000577
578/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
579/// if the match fails. At this point, we already know that the opcode for N
580/// matches, and the SDNode for the result has the RootName specified name.
581void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
582 const std::string &RootName,
583 const std::string &ChainSuffix,
584 bool &FoundChain) {
585
586 // Save loads/stores matched by a pattern.
587 if (!N->isLeaf() && N->getName().empty()) {
588 if (NodeHasProperty(N, SDNPMemOperand, CGP))
589 LSI.push_back(getNodeName(RootName));
590 }
591
592 bool isRoot = (P == NULL);
593 // Emit instruction predicates. Each predicate is just a string for now.
594 if (isRoot) {
595 // Record input varargs info.
596 NumInputRootOps = N->getNumChildren();
597
598 if (DisablePatternForFastISel(N, CGP))
599 emitCheck("OptLevel != CodeGenOpt::None");
600
601 emitCheck(PredicateCheck);
602 }
603
604 if (N->isLeaf()) {
605 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
606 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
607 ")->getSExtValue() == INT64_C(" +
608 itostr(II->getValue()) + ")");
609 return;
610 } else if (!NodeIsComplexPattern(N)) {
611 assert(0 && "Cannot match this as a leaf value!");
612 abort();
613 }
614 }
615
616 // If this node has a name associated with it, capture it in VariableMap. If
617 // we already saw this in the pattern, emit code to verify dagness.
618 if (!N->getName().empty()) {
619 std::string &VarMapEntry = VariableMap[N->getName()];
620 if (VarMapEntry.empty()) {
621 VarMapEntry = RootName;
622 } else {
623 // If we get here, this is a second reference to a specific name. Since
624 // we already have checked that the first reference is valid, we don't
625 // have to recursively match it, just check that it's the same as the
626 // previously named thing.
627 emitCheck(VarMapEntry + " == " + RootName);
628 return;
629 }
630
631 if (!N->isLeaf())
632 OperatorMap[N->getName()] = N->getOperator();
633 }
634
635
636 // Emit code to load the child nodes and match their contents recursively.
637 unsigned OpNo = 0;
638 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
639 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
640 bool EmittedUseCheck = false;
641 if (HasChain) {
642 if (NodeHasChain)
643 OpNo = 1;
644 if (!isRoot) {
645 // Multiple uses of actual result?
646 emitCheck(getValueName(RootName) + ".hasOneUse()");
647 EmittedUseCheck = true;
648 if (NodeHasChain) {
649 // If the immediate use can somehow reach this node through another
650 // path, then can't fold it either or it will create a cycle.
651 // e.g. In the following diagram, XX can reach ld through YY. If
652 // ld is folded into XX, then YY is both a predecessor and a successor
653 // of XX.
654 //
655 // [ld]
656 // ^ ^
657 // | |
658 // / \---
659 // / [YY]
660 // | ^
661 // [XX]-------|
662 bool NeedCheck = P != Pattern;
663 if (!NeedCheck) {
664 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
665 NeedCheck =
666 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
667 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
668 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
669 PInfo.getNumOperands() > 1 ||
670 PInfo.hasProperty(SDNPHasChain) ||
671 PInfo.hasProperty(SDNPInFlag) ||
672 PInfo.hasProperty(SDNPOptInFlag);
673 }
674
675 if (NeedCheck) {
676 std::string ParentName(RootName.begin(), RootName.end()-1);
677 emitCheck("IsLegalAndProfitableToFold(" + getNodeName(RootName) +
678 ", " + getNodeName(ParentName) + ", N)");
679 }
680 }
681 }
682
683 if (NodeHasChain) {
684 if (FoundChain) {
685 emitCheck("(" + ChainName + ".getNode() == " +
686 getNodeName(RootName) + " || "
687 "IsChainCompatible(" + ChainName + ".getNode(), " +
688 getNodeName(RootName) + "))");
689 OrigChains.push_back(std::make_pair(ChainName,
690 getValueName(RootName)));
691 } else
692 FoundChain = true;
693 ChainName = "Chain" + ChainSuffix;
694 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
695 "->getOperand(0);");
696 }
697 }
698
699 // Don't fold any node which reads or writes a flag and has multiple uses.
700 // FIXME: We really need to separate the concepts of flag and "glue". Those
701 // real flag results, e.g. X86CMP output, can have multiple uses.
702 // FIXME: If the optional incoming flag does not exist. Then it is ok to
703 // fold it.
704 if (!isRoot &&
705 (PatternHasProperty(N, SDNPInFlag, CGP) ||
706 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
707 PatternHasProperty(N, SDNPOutFlag, CGP))) {
708 if (!EmittedUseCheck) {
709 // Multiple uses of actual result?
710 emitCheck(getValueName(RootName) + ".hasOneUse()");
711 }
712 }
713
714 // If there are node predicates for this, emit the calls.
715 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
716 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
717
718 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
719 // a constant without a predicate fn that has more that one bit set, handle
720 // this as a special case. This is usually for targets that have special
721 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
722 // handling stuff). Using these instructions is often far more efficient
723 // than materializing the constant. Unfortunately, both the instcombiner
724 // and the dag combiner can often infer that bits are dead, and thus drop
725 // them from the mask in the dag. For example, it might turn 'AND X, 255'
726 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
727 // to handle this.
728 if (!N->isLeaf() &&
729 (N->getOperator()->getName() == "and" ||
730 N->getOperator()->getName() == "or") &&
731 N->getChild(1)->isLeaf() &&
732 N->getChild(1)->getPredicateFns().empty()) {
733 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
734 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
735 emitInit("SDValue " + RootName + "0" + " = " +
736 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
737 emitInit("SDValue " + RootName + "1" + " = " +
738 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
739
740 unsigned NTmp = TmpNo++;
741 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
742 " = dyn_cast<ConstantSDNode>(" +
743 getNodeName(RootName + "1") + ");");
744 emitCheck("Tmp" + utostr(NTmp));
745 const char *MaskPredicate = N->getOperator()->getName() == "or"
746 ? "CheckOrMask(" : "CheckAndMask(";
747 emitCheck(MaskPredicate + getValueName(RootName + "0") +
748 ", Tmp" + utostr(NTmp) +
749 ", INT64_C(" + itostr(II->getValue()) + "))");
750
751 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
752 ChainSuffix + utostr(0), FoundChain);
753 return;
754 }
755 }
756 }
757
758 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
759 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
760 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
761
762 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
763 ChainSuffix + utostr(OpNo), FoundChain);
764 }
765
766 // Handle cases when root is a complex pattern.
767 const ComplexPattern *CP;
768 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
769 std::string Fn = CP->getSelectFunc();
770 unsigned NumOps = CP->getNumOperands();
771 for (unsigned i = 0; i < NumOps; ++i) {
772 emitDecl("CPTmp" + RootName + "_" + utostr(i));
773 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
774 }
775 if (CP->hasProperty(SDNPHasChain)) {
776 emitDecl("CPInChain");
777 emitDecl("Chain" + ChainSuffix);
778 emitCode("SDValue CPInChain;");
779 emitCode("SDValue Chain" + ChainSuffix + ";");
780 }
781
782 std::string Code = Fn + "(" +
783 getNodeName(RootName) + ", " +
784 getValueName(RootName);
785 for (unsigned i = 0; i < NumOps; i++)
786 Code += ", CPTmp" + RootName + "_" + utostr(i);
787 if (CP->hasProperty(SDNPHasChain)) {
788 ChainName = "Chain" + ChainSuffix;
789 Code += ", CPInChain, Chain" + ChainSuffix;
790 }
791 emitCheck(Code + ")");
792 }
793}
794
795void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
796 TreePatternNode *Parent,
797 const std::string &RootName,
798 const std::string &ChainSuffix,
799 bool &FoundChain) {
800 if (!Child->isLeaf()) {
801 // If it's not a leaf, recursively match.
802 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
803 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
804 CInfo.getEnumName());
805 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
806 bool HasChain = false;
807 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
808 HasChain = true;
809 FoldedChains.push_back(std::make_pair(getValueName(RootName),
810 CInfo.getNumResults()));
811 }
812 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
813 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
814 "Pattern folded multiple nodes which produce flags?");
815 FoldedFlag = std::make_pair(getValueName(RootName),
816 CInfo.getNumResults() + (unsigned)HasChain);
817 }
818 } else {
819 // If this child has a name associated with it, capture it in VarMap. If
820 // we already saw this in the pattern, emit code to verify dagness.
821 if (!Child->getName().empty()) {
822 std::string &VarMapEntry = VariableMap[Child->getName()];
823 if (VarMapEntry.empty()) {
824 VarMapEntry = getValueName(RootName);
825 } else {
826 // If we get here, this is a second reference to a specific name.
827 // Since we already have checked that the first reference is valid,
828 // we don't have to recursively match it, just check that it's the
829 // same as the previously named thing.
830 emitCheck(VarMapEntry + " == " + getValueName(RootName));
831 Duplicates.insert(getValueName(RootName));
832 return;
833 }
834 }
835
836 // Handle leaves of various types.
837 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
838 Record *LeafRec = DI->getDef();
839 if (LeafRec->isSubClassOf("RegisterClass") ||
840 LeafRec->isSubClassOf("PointerLikeRegClass")) {
841 // Handle register references. Nothing to do here.
842 } else if (LeafRec->isSubClassOf("Register")) {
843 // Handle register references.
844 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
845 // Handle complex pattern.
846 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
847 std::string Fn = CP->getSelectFunc();
848 unsigned NumOps = CP->getNumOperands();
849 for (unsigned i = 0; i < NumOps; ++i) {
850 emitDecl("CPTmp" + RootName + "_" + utostr(i));
851 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
852 }
853 if (CP->hasProperty(SDNPHasChain)) {
854 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
855 FoldedChains.push_back(std::make_pair("CPInChain",
856 PInfo.getNumResults()));
857 ChainName = "Chain" + ChainSuffix;
858 emitDecl("CPInChain");
859 emitDecl(ChainName);
860 emitCode("SDValue CPInChain;");
861 emitCode("SDValue " + ChainName + ";");
862 }
863
864 std::string Code = Fn + "(N, ";
865 if (CP->hasProperty(SDNPHasChain)) {
866 std::string ParentName(RootName.begin(), RootName.end()-1);
867 Code += getValueName(ParentName) + ", ";
868 }
869 Code += getValueName(RootName);
870 for (unsigned i = 0; i < NumOps; i++)
871 Code += ", CPTmp" + RootName + "_" + utostr(i);
872 if (CP->hasProperty(SDNPHasChain))
873 Code += ", CPInChain, Chain" + ChainSuffix;
874 emitCheck(Code + ")");
875 } else if (LeafRec->getName() == "srcvalue") {
876 // Place holder for SRCVALUE nodes. Nothing to do here.
877 } else if (LeafRec->isSubClassOf("ValueType")) {
878 // Make sure this is the specified value type.
879 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
880 ")->getVT() == MVT::" + LeafRec->getName());
881 } else if (LeafRec->isSubClassOf("CondCode")) {
882 // Make sure this is the specified cond code.
883 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
884 ")->get() == ISD::" + LeafRec->getName());
885 } else {
886#ifndef NDEBUG
887 Child->dump();
888 errs() << " ";
889#endif
890 assert(0 && "Unknown leaf type!");
891 }
892
893 // If there are node predicates for this, emit the calls.
894 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
895 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
896 ")");
897 } else if (IntInit *II =
898 dynamic_cast<IntInit*>(Child->getLeafValue())) {
899 unsigned NTmp = TmpNo++;
900 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
901 " = dyn_cast<ConstantSDNode>("+
902 getNodeName(RootName) + ");");
903 emitCheck("Tmp" + utostr(NTmp));
904 unsigned CTmp = TmpNo++;
905 emitCode("int64_t CN"+ utostr(CTmp) +
906 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
907 emitCheck("CN" + utostr(CTmp) + " == "
908 "INT64_C(" +itostr(II->getValue()) + ")");
909 } else {
910#ifndef NDEBUG
911 Child->dump();
912#endif
913 assert(0 && "Unknown leaf type!");
914 }
915 }
916}
917
918/// EmitResultCode - Emit the action for a pattern. Now that it has matched
919/// we actually have to build a DAG!
920std::vector<std::string>
921PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
922 std::vector<Record*> DstRegs,
923 bool InFlagDecled, bool ResNodeDecled,
924 bool LikeLeaf, bool isRoot) {
925 // List of arguments of getMachineNode() or SelectNodeTo().
926 std::vector<std::string> NodeOps;
927 // This is something selected from the pattern we matched.
928 if (!N->getName().empty()) {
929 const std::string &VarName = N->getName();
930 std::string Val = VariableMap[VarName];
931 bool ModifiedVal = false;
932 if (Val.empty()) {
933 errs() << "Variable '" << VarName << " referenced but not defined "
934 << "and not caught earlier!\n";
935 abort();
936 }
937 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
938 // Already selected this operand, just return the tmpval.
939 NodeOps.push_back(getValueName(Val));
940 return NodeOps;
941 }
942
943 const ComplexPattern *CP;
944 unsigned ResNo = TmpNo++;
945 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
946 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
947 std::string CastType;
948 std::string TmpVar = "Tmp" + utostr(ResNo);
949 switch (N->getTypeNum(0)) {
950 default:
951 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
952 << " type as an immediate constant. Aborting\n";
953 abort();
954 case MVT::i1: CastType = "bool"; break;
955 case MVT::i8: CastType = "unsigned char"; break;
956 case MVT::i16: CastType = "unsigned short"; break;
957 case MVT::i32: CastType = "unsigned"; break;
958 case MVT::i64: CastType = "uint64_t"; break;
959 }
960 emitCode("SDValue " + TmpVar +
961 " = CurDAG->getTargetConstant(((" + CastType +
962 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
963 getEnumName(N->getTypeNum(0)) + ");");
964 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
965 // value if used multiple times by this pattern result.
966 Val = TmpVar;
967 ModifiedVal = true;
968 NodeOps.push_back(getValueName(Val));
969 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
970 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
971 std::string TmpVar = "Tmp" + utostr(ResNo);
972 emitCode("SDValue " + TmpVar +
973 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
974 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
975 Val + ")->getValueType(0));");
976 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
977 // value if used multiple times by this pattern result.
978 Val = TmpVar;
979 ModifiedVal = true;
980 NodeOps.push_back(getValueName(Val));
981 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
982 Record *Op = OperatorMap[N->getName()];
983 // Transform ExternalSymbol to TargetExternalSymbol
984 if (Op && Op->getName() == "externalsym") {
985 std::string TmpVar = "Tmp"+utostr(ResNo);
986 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
987 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
988 Val + ")->getSymbol(), " +
989 getEnumName(N->getTypeNum(0)) + ");");
990 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
991 // this value if used multiple times by this pattern result.
992 Val = TmpVar;
993 ModifiedVal = true;
994 }
995 NodeOps.push_back(getValueName(Val));
996 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
997 || N->getOperator()->getName() == "tglobaltlsaddr")) {
998 Record *Op = OperatorMap[N->getName()];
999 // Transform GlobalAddress to TargetGlobalAddress
1000 if (Op && (Op->getName() == "globaladdr" ||
1001 Op->getName() == "globaltlsaddr")) {
1002 std::string TmpVar = "Tmp" + utostr(ResNo);
1003 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
1004 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
1005 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
1006 ");");
1007 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
1008 // this value if used multiple times by this pattern result.
1009 Val = TmpVar;
1010 ModifiedVal = true;
1011 }
1012 NodeOps.push_back(getValueName(Val));
1013 } else if (!N->isLeaf()
1014 && (N->getOperator()->getName() == "texternalsym"
1015 || N->getOperator()->getName() == "tconstpool")) {
1016 // Do not rewrite the variable name, since we don't generate a new
1017 // temporary.
1018 NodeOps.push_back(getValueName(Val));
1019 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
1020 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
1021 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
1022 }
1023 } else {
1024 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
1025 // node even if it isn't one. Don't select it.
1026 if (!LikeLeaf) {
1027 if (isRoot && N->isLeaf()) {
1028 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
1029 emitCode("return NULL;");
1030 }
1031 }
1032 NodeOps.push_back(getValueName(Val));
1033 }
1034
1035 if (ModifiedVal) {
1036 VariableMap[VarName] = Val;
1037 }
1038 return NodeOps;
1039 }
1040 if (N->isLeaf()) {
1041 // If this is an explicit register reference, handle it.
1042 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
1043 unsigned ResNo = TmpNo++;
1044 if (DI->getDef()->isSubClassOf("Register")) {
1045 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
1046 getQualifiedName(DI->getDef()) + ", " +
1047 getEnumName(N->getTypeNum(0)) + ");");
1048 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1049 return NodeOps;
1050 } else if (DI->getDef()->getName() == "zero_reg") {
1051 emitCode("SDValue Tmp" + utostr(ResNo) +
1052 " = CurDAG->getRegister(0, " +
1053 getEnumName(N->getTypeNum(0)) + ");");
1054 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1055 return NodeOps;
1056 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
1057 // Handle a reference to a register class. This is used
1058 // in COPY_TO_SUBREG instructions.
1059 emitCode("SDValue Tmp" + utostr(ResNo) +
1060 " = CurDAG->getTargetConstant(" +
1061 getQualifiedName(DI->getDef()) + "RegClassID, " +
1062 "MVT::i32);");
1063 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1064 return NodeOps;
1065 }
1066 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
1067 unsigned ResNo = TmpNo++;
1068 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
1069 emitCode("SDValue Tmp" + utostr(ResNo) +
1070 " = CurDAG->getTargetConstant(0x" +
1071 utohexstr((uint64_t) II->getValue()) +
1072 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
1073 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
1074 return NodeOps;
1075 }
1076
1077#ifndef NDEBUG
1078 N->dump();
1079#endif
1080 assert(0 && "Unknown leaf type!");
1081 return NodeOps;
1082 }
1083
1084 Record *Op = N->getOperator();
1085 if (Op->isSubClassOf("Instruction")) {
1086 const CodeGenTarget &CGT = CGP.getTargetInfo();
1087 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
1088 const DAGInstruction &Inst = CGP.getInstruction(Op);
1089 const TreePattern *InstPat = Inst.getPattern();
1090 // FIXME: Assume actual pattern comes before "implicit".
1091 TreePatternNode *InstPatNode =
1092 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
1093 : (InstPat ? InstPat->getTree(0) : NULL);
1094 if (InstPatNode && !InstPatNode->isLeaf() &&
1095 InstPatNode->getOperator()->getName() == "set") {
1096 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
1097 }
1098 bool IsVariadic = isRoot && II.isVariadic;
1099 // FIXME: fix how we deal with physical register operands.
1100 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1101 bool HasImpResults = isRoot && DstRegs.size() > 0;
1102 bool NodeHasOptInFlag = isRoot &&
1103 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
1104 bool NodeHasInFlag = isRoot &&
1105 PatternHasProperty(Pattern, SDNPInFlag, CGP);
1106 bool NodeHasOutFlag = isRoot &&
1107 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
1108 bool NodeHasChain = InstPatNode &&
1109 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
1110 bool InputHasChain = isRoot &&
1111 NodeHasProperty(Pattern, SDNPHasChain, CGP);
1112 unsigned NumResults = Inst.getNumResults();
1113 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1114
1115 // Record output varargs info.
1116 OutputIsVariadic = IsVariadic;
1117
1118 if (NodeHasOptInFlag) {
1119 emitCode("bool HasInFlag = "
1120 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1121 "MVT::Flag);");
1122 }
1123 if (IsVariadic)
1124 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1125
1126 // How many results is this pattern expected to produce?
1127 unsigned NumPatResults = 0;
1128 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1129 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1130 if (VT != MVT::isVoid && VT != MVT::Flag)
1131 NumPatResults++;
1132 }
1133
1134 if (OrigChains.size() > 0) {
1135 // The original input chain is being ignored. If it is not just
1136 // pointing to the op that's being folded, we should create a
1137 // TokenFactor with it and the chain of the folded op as the new chain.
1138 // We could potentially be doing multiple levels of folding, in that
1139 // case, the TokenFactor can have more operands.
1140 emitCode("SmallVector<SDValue, 8> InChains;");
1141 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1142 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1143 OrigChains[i].second + ".getNode()) {");
1144 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1145 emitCode("}");
1146 }
1147 emitCode("InChains.push_back(" + ChainName + ");");
1148 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1149 "N->getDebugLoc(), MVT::Other, "
1150 "&InChains[0], InChains.size());");
1151 if (GenDebug) {
1152 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1153 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1154 }
1155 }
1156
1157 // Loop over all of the operands of the instruction pattern, emitting code
1158 // to fill them all in. The node 'N' usually has number children equal to
1159 // the number of input operands of the instruction. However, in cases
1160 // where there are predicate operands for an instruction, we need to fill
1161 // in the 'execute always' values. Match up the node operands to the
1162 // instruction operands to do this.
1163 std::vector<std::string> AllOps;
1164 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1165 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1166 std::vector<std::string> Ops;
1167
1168 // Determine what to emit for this operand.
1169 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1170 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1171 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1172 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1173 // This is a predicate or optional def operand; emit the
1174 // 'default ops' operands.
1175 const DAGDefaultOperand &DefaultOp =
1176 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1177 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1178 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1179 InFlagDecled, ResNodeDecled);
1180 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1181 }
1182 } else {
1183 // Otherwise this is a normal operand or a predicate operand without
1184 // 'execute always'; emit it.
1185 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1186 InFlagDecled, ResNodeDecled);
1187 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1188 ++ChildNo;
1189 }
1190 }
1191
1192 // Emit all the chain and CopyToReg stuff.
1193 bool ChainEmitted = NodeHasChain;
1194 if (NodeHasInFlag || HasImpInputs)
1195 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1196 InFlagDecled, ResNodeDecled, true);
1197 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1198 if (!InFlagDecled) {
1199 emitCode("SDValue InFlag(0, 0);");
1200 InFlagDecled = true;
1201 }
1202 if (NodeHasOptInFlag) {
1203 emitCode("if (HasInFlag) {");
1204 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1205 emitCode("}");
1206 }
1207 }
1208
1209 unsigned ResNo = TmpNo++;
1210
1211 unsigned OpsNo = OpcNo;
1212 std::string CodePrefix;
1213 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1214 std::deque<std::string> After;
1215 std::string NodeName;
1216 if (!isRoot) {
1217 NodeName = "Tmp" + utostr(ResNo);
1218 CodePrefix = "SDValue " + NodeName + "(";
1219 } else {
1220 NodeName = "ResNode";
1221 if (!ResNodeDecled) {
1222 CodePrefix = "SDNode *" + NodeName + " = ";
1223 ResNodeDecled = true;
1224 } else
1225 CodePrefix = NodeName + " = ";
1226 }
1227
1228 std::string Code = "Opc" + utostr(OpcNo);
1229
1230 if (!isRoot || (InputHasChain && !NodeHasChain))
1231 // For call to "getMachineNode()".
1232 Code += ", N->getDebugLoc()";
1233
1234 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1235
1236 // Output order: results, chain, flags
1237 // Result types.
1238 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1239 Code += ", VT" + utostr(VTNo);
1240 emitVT(getEnumName(N->getTypeNum(0)));
1241 }
1242 // Add types for implicit results in physical registers, scheduler will
1243 // care of adding copyfromreg nodes.
1244 for (unsigned i = 0; i < NumDstRegs; i++) {
1245 Record *RR = DstRegs[i];
1246 if (RR->isSubClassOf("Register")) {
1247 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1248 Code += ", " + getEnumName(RVT);
1249 }
1250 }
1251 if (NodeHasChain)
1252 Code += ", MVT::Other";
1253 if (NodeHasOutFlag)
1254 Code += ", MVT::Flag";
1255
1256 // Inputs.
1257 if (IsVariadic) {
1258 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1259 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1260 AllOps.clear();
1261
1262 // Figure out whether any operands at the end of the op list are not
1263 // part of the variable section.
1264 std::string EndAdjust;
1265 if (NodeHasInFlag || HasImpInputs)
1266 EndAdjust = "-1"; // Always has one flag.
1267 else if (NodeHasOptInFlag)
1268 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1269
1270 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1271 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1272
1273 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1274 emitCode("}");
1275 }
1276
1277 // Populate MemRefs with entries for each memory accesses covered by
1278 // this pattern.
1279 if (isRoot && !LSI.empty()) {
1280 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1281 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1282 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1283 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1284 emitCode(MemRefs + "[" + utostr(i) + "] = "
1285 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1286 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1287 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1288 ");");
1289 }
1290
1291 if (NodeHasChain) {
1292 if (IsVariadic)
1293 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1294 else
1295 AllOps.push_back(ChainName);
1296 }
1297
1298 if (IsVariadic) {
1299 if (NodeHasInFlag || HasImpInputs)
1300 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1301 else if (NodeHasOptInFlag) {
1302 emitCode("if (HasInFlag)");
1303 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1304 }
1305 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1306 ".size()";
1307 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1308 AllOps.push_back("InFlag");
1309
1310 unsigned NumOps = AllOps.size();
1311 if (NumOps) {
1312 if (!NodeHasOptInFlag && NumOps < 4) {
1313 for (unsigned i = 0; i != NumOps; ++i)
1314 Code += ", " + AllOps[i];
1315 } else {
1316 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1317 for (unsigned i = 0; i != NumOps; ++i) {
1318 OpsCode += AllOps[i];
1319 if (i != NumOps-1)
1320 OpsCode += ", ";
1321 }
1322 emitCode(OpsCode + " };");
1323 Code += ", Ops" + utostr(OpsNo) + ", ";
1324 if (NodeHasOptInFlag) {
1325 Code += "HasInFlag ? ";
1326 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1327 } else
1328 Code += utostr(NumOps);
1329 }
1330 }
1331
1332 if (!isRoot)
1333 Code += "), 0";
1334
1335 std::vector<std::string> ReplaceFroms;
1336 std::vector<std::string> ReplaceTos;
1337 if (!isRoot) {
1338 NodeOps.push_back("Tmp" + utostr(ResNo));
1339 } else {
1340
1341 if (NodeHasOutFlag) {
1342 if (!InFlagDecled) {
1343 After.push_back("SDValue InFlag(ResNode, " +
1344 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1345 ");");
1346 InFlagDecled = true;
1347 } else
1348 After.push_back("InFlag = SDValue(ResNode, " +
1349 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1350 ");");
1351 }
1352
1353 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1354 ReplaceFroms.push_back("SDValue(" +
1355 FoldedChains[j].first + ".getNode(), " +
1356 utostr(FoldedChains[j].second) +
1357 ")");
1358 ReplaceTos.push_back("SDValue(ResNode, " +
1359 utostr(NumResults+NumDstRegs) + ")");
1360 }
1361
1362 if (NodeHasOutFlag) {
1363 if (FoldedFlag.first != "") {
1364 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1365 utostr(FoldedFlag.second) + ")");
1366 ReplaceTos.push_back("InFlag");
1367 } else {
1368 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
1369 ReplaceFroms.push_back("SDValue(N, " +
1370 utostr(NumPatResults + (unsigned)InputHasChain)
1371 + ")");
1372 ReplaceTos.push_back("InFlag");
1373 }
1374 }
1375
1376 if (!ReplaceFroms.empty() && InputHasChain) {
1377 ReplaceFroms.push_back("SDValue(N, " +
1378 utostr(NumPatResults) + ")");
1379 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1380 ChainName + ".getResNo()" + ")");
1381 ChainAssignmentNeeded |= NodeHasChain;
1382 }
1383
1384 // User does not expect the instruction would produce a chain!
1385 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1386 ;
1387 } else if (InputHasChain && !NodeHasChain) {
1388 // One of the inner node produces a chain.
1389 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1390 ReplaceFroms.push_back("SDValue(N, " +
1391 utostr(NumPatResults) + ")");
1392 ReplaceTos.push_back(ChainName);
1393 }
1394 }
1395
1396 if (ChainAssignmentNeeded) {
1397 // Remember which op produces the chain.
1398 std::string ChainAssign;
1399 if (!isRoot)
1400 ChainAssign = ChainName + " = SDValue(" + NodeName +
1401 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1402 else
1403 ChainAssign = ChainName + " = SDValue(" + NodeName +
1404 ", " + utostr(NumResults+NumDstRegs) + ");";
1405
1406 After.push_front(ChainAssign);
1407 }
1408
1409 if (ReplaceFroms.size() == 1) {
1410 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1411 ReplaceTos[0] + ");");
1412 } else if (!ReplaceFroms.empty()) {
1413 After.push_back("const SDValue Froms[] = {");
1414 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1415 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1416 After.push_back("};");
1417 After.push_back("const SDValue Tos[] = {");
1418 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1419 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1420 After.push_back("};");
1421 After.push_back("ReplaceUses(Froms, Tos, " +
1422 itostr(ReplaceFroms.size()) + ");");
1423 }
1424
1425 // We prefer to use SelectNodeTo since it avoids allocation when
1426 // possible and it avoids CSE map recalculation for the node's
1427 // users, however it's tricky to use in a non-root context.
1428 //
1429 // We also don't use SelectNodeTo if the pattern replacement is being
1430 // used to jettison a chain result, since morphing the node in place
1431 // would leave users of the chain dangling.
1432 //
1433 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1434 Code = "CurDAG->getMachineNode(" + Code;
1435 } else {
1436 Code = "CurDAG->SelectNodeTo(N, " + Code;
1437 }
1438 if (isRoot) {
1439 if (After.empty())
1440 CodePrefix = "return ";
1441 else
1442 After.push_back("return ResNode;");
1443 }
1444
1445 emitCode(CodePrefix + Code + ");");
1446
1447 if (GenDebug) {
1448 if (!isRoot) {
1449 emitCode("CurDAG->setSubgraphColor(" +
1450 NodeName +".getNode(), \"yellow\");");
1451 emitCode("CurDAG->setSubgraphColor(" +
1452 NodeName +".getNode(), \"black\");");
1453 } else {
1454 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1455 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1456 }
1457 }
1458
1459 for (unsigned i = 0, e = After.size(); i != e; ++i)
1460 emitCode(After[i]);
1461
1462 return NodeOps;
1463 }
1464 if (Op->isSubClassOf("SDNodeXForm")) {
1465 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1466 // PatLeaf node - the operand may or may not be a leaf node. But it should
1467 // behave like one.
1468 std::vector<std::string> Ops =
1469 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1470 ResNodeDecled, true);
1471 unsigned ResNo = TmpNo++;
1472 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1473 + "(" + Ops.back() + ".getNode());");
1474 NodeOps.push_back("Tmp" + utostr(ResNo));
1475 if (isRoot)
1476 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1477 return NodeOps;
1478 }
1479
1480 N->dump();
1481 errs() << "\n";
1482 throw std::string("Unknown node in result pattern!");
1483}
1484
1485
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001486/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1487/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001488/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001489void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001490 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001491 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001492 std::vector<std::string> &TargetOpcodes,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001493 std::vector<std::string> &TargetVTs,
1494 bool &OutputIsVariadic,
1495 unsigned &NumInputRootOps) {
1496 OutputIsVariadic = false;
1497 NumInputRootOps = 0;
1498
Dan Gohman22bb3112008-08-22 00:20:26 +00001499 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001500 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001501 GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001502 TargetOpcodes, TargetVTs,
1503 OutputIsVariadic, NumInputRootOps);
Evan Chengb915f312005-12-09 22:45:35 +00001504
Chris Lattner8fc35682005-09-23 23:16:51 +00001505 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001506 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001507 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001508
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001509 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner200c57e2008-01-05 22:58:54 +00001510 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001511
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001512 // At this point, we know that we structurally match the pattern, but the
1513 // types of the nodes may not match. Figure out the fewest number of type
1514 // comparisons we need to emit. For example, if there is only one integer
1515 // type supported by a target, there should be no type comparisons at all for
1516 // integer patterns!
1517 //
1518 // To figure out the fewest number of type checks needed, clone the pattern,
1519 // remove the types, then perform type inference on the pattern as a whole.
1520 // If there are unresolved types, emit an explicit check for those types,
1521 // apply the type to the tree, then rerun type inference. Iterate until all
1522 // types are resolved.
1523 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001524 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001525 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001526
1527 do {
1528 // Resolve/propagate as many types as possible.
1529 try {
1530 bool MadeChange = true;
1531 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001532 MadeChange = Pat->ApplyTypeConstraints(TP,
1533 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001534 } catch (...) {
1535 assert(0 && "Error: could not find consistent types for something we"
1536 " already decided was ok!");
1537 abort();
1538 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001539
Chris Lattner7e82f132005-10-15 21:34:21 +00001540 // Insert a check for an unresolved type and add it to the tree. If we find
1541 // an unresolved type to add a check for, this returns true and we iterate,
1542 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001543 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001544
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001545 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001546 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001547 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001548}
1549
Chris Lattner24e00a42006-01-29 04:41:05 +00001550/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1551/// a line causes any of them to be empty, remove them and return true when
1552/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001553static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001554 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001555 &Patterns) {
1556 bool ErasedPatterns = false;
1557 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1558 Patterns[i].second.pop_back();
1559 if (Patterns[i].second.empty()) {
1560 Patterns.erase(Patterns.begin()+i);
1561 --i; --e;
1562 ErasedPatterns = true;
1563 }
1564 }
1565 return ErasedPatterns;
1566}
1567
Chris Lattner8bc74722006-01-29 04:25:26 +00001568/// EmitPatterns - Emit code for at least one pattern, but try to group common
1569/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001570void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001571 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001572 &Patterns, unsigned Indent,
Daniel Dunbar1a551802009-07-03 00:10:29 +00001573 raw_ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001574 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001575 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001576 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001577
1578 if (Patterns.empty()) return;
1579
Chris Lattner24e00a42006-01-29 04:41:05 +00001580 // Figure out how many patterns share the next code line. Explicitly copy
1581 // FirstCodeLine so that we don't invalidate a reference when changing
1582 // Patterns.
1583 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001584 unsigned LastMatch = Patterns.size()-1;
1585 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1586 --LastMatch;
1587
1588 // If not all patterns share this line, split the list into two pieces. The
1589 // first chunk will use this line, the second chunk won't.
1590 if (LastMatch != 0) {
1591 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1592 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1593
1594 // FIXME: Emit braces?
1595 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001596 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001597 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1598 Pattern.getSrcPattern()->print(OS);
1599 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1600 Pattern.getDstPattern()->print(OS);
1601 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001602 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001603 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001604 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001605 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001606 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001607 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001608 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001609 }
Evan Cheng676d7312006-08-26 00:59:04 +00001610 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001611 OS << std::string(Indent, ' ') << "{\n";
1612 Indent += 2;
1613 }
1614 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001615 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001616 Indent -= 2;
1617 OS << std::string(Indent, ' ') << "}\n";
1618 }
1619
1620 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001621 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001622 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1623 Pattern.getSrcPattern()->print(OS);
1624 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1625 Pattern.getDstPattern()->print(OS);
1626 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001627 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001628 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001629 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001630 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001631 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001632 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001633 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001634 }
1635 EmitPatterns(Other, Indent, OS);
1636 return;
1637 }
1638
Chris Lattner24e00a42006-01-29 04:41:05 +00001639 // Remove this code from all of the patterns that share it.
1640 bool ErasedPatterns = EraseCodeLine(Patterns);
1641
Evan Cheng676d7312006-08-26 00:59:04 +00001642 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001643
1644 // Otherwise, every pattern in the list has this line. Emit it.
1645 if (!isPredicate) {
1646 // Normal code.
1647 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1648 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001649 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1650
1651 // If the next code line is another predicate, and if all of the pattern
1652 // in this group share the same next line, emit it inline now. Do this
1653 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001654 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda4231f2009-03-26 16:17:51 +00001655 // Check that all of the patterns in Patterns end with the same predicate.
Chris Lattner24e00a42006-01-29 04:41:05 +00001656 bool AllEndWithSamePredicate = true;
1657 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1658 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1659 AllEndWithSamePredicate = false;
1660 break;
1661 }
1662 // If all of the predicates aren't the same, we can't share them.
1663 if (!AllEndWithSamePredicate) break;
1664
1665 // Otherwise we can. Emit it shared now.
1666 OS << " &&\n" << std::string(Indent+4, ' ')
1667 << Patterns.back().second.back().second;
1668 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001669 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001670
1671 OS << ") {\n";
1672 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001673 }
1674
1675 EmitPatterns(Patterns, Indent, OS);
1676
1677 if (isPredicate)
1678 OS << std::string(Indent-2, ' ') << "}\n";
1679}
1680
Evan Cheng892aaf82006-11-08 23:01:03 +00001681static std::string getLegalCName(std::string OpName) {
1682 std::string::size_type pos = OpName.find("::");
1683 if (pos != std::string::npos)
1684 OpName.replace(pos, 2, "_");
1685 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001686}
1687
Daniel Dunbar1a551802009-07-03 00:10:29 +00001688void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001689 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner6cefb772008-01-05 22:25:12 +00001690
Dan Gohman1e0ee4b2008-08-20 21:45:57 +00001691 // Get the namespace to insert instructions into.
1692 std::string InstNS = Target.getInstNamespace();
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001693 if (!InstNS.empty()) InstNS += "::";
1694
Chris Lattner602f6922006-01-04 00:25:00 +00001695 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001696 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001697 // All unique target node emission functions.
1698 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001699 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001700 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001701 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001702
1703 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001704 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001705 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001706 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001707 } else {
1708 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001709 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001710 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001711 push_back(&Pattern);
Chris Lattner200c57e2008-01-05 22:58:54 +00001712 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001713 std::vector<Record*> OpNodes = CP->getRootNodes();
1714 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001715 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1716 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001717 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001718 }
1719 } else {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001720 errs() << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001721 Node->dump();
Daniel Dunbar1a551802009-07-03 00:10:29 +00001722 errs() << "' on tree pattern '";
1723 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001724 exit(1);
1725 }
1726 }
1727 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001728
1729 // For each opcode, there might be multiple select functions, one per
1730 // ValueType of the node (or its first operand if it doesn't produce a
1731 // non-chain result.
1732 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1733
Chris Lattner602f6922006-01-04 00:25:00 +00001734 // Emit one Select_* method for each top-level opcode. We do this instead of
1735 // emitting one giant switch statement to support compilers where this will
1736 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001737 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001738 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1739 PBOI != E; ++PBOI) {
1740 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001741 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001742 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1743
Chris Lattner706d2d32006-08-09 16:44:44 +00001744 // Split them into groups by type.
Owen Anderson825b72b2009-08-11 20:47:22 +00001745 std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001746 std::vector<const PatternToMatch*> > PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001747 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001748 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001749 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner9783d622008-08-26 07:01:28 +00001750 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Chris Lattner706d2d32006-08-09 16:44:44 +00001751 }
1752
Owen Anderson825b72b2009-08-11 20:47:22 +00001753 for (std::map<MVT::SimpleValueType,
Duncan Sands83ec4b62008-06-06 12:08:01 +00001754 std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001755 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1756 ++II) {
Owen Anderson825b72b2009-08-11 20:47:22 +00001757 MVT::SimpleValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001758 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman0540e172008-10-15 06:17:21 +00001759 typedef std::pair<unsigned, std::string> CodeLine;
1760 typedef std::vector<CodeLine> CodeList;
1761 typedef CodeList::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001762
Chris Lattner60d81392008-01-05 22:30:17 +00001763 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001764 std::vector<std::vector<std::string> > PatternOpcodes;
1765 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001766 std::vector<std::set<std::string> > PatternDecls;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001767 std::vector<bool> OutputIsVariadicFlags;
1768 std::vector<unsigned> NumInputRootOpsCounts;
Chris Lattner706d2d32006-08-09 16:44:44 +00001769 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1770 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001771 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001772 std::vector<std::string> TargetOpcodes;
1773 std::vector<std::string> TargetVTs;
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001774 bool OutputIsVariadic;
1775 unsigned NumInputRootOps;
Chris Lattner706d2d32006-08-09 16:44:44 +00001776 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001777 TargetOpcodes, TargetVTs,
1778 OutputIsVariadic, NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001779 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1780 PatternDecls.push_back(GeneratedDecl);
1781 PatternOpcodes.push_back(TargetOpcodes);
1782 PatternVTs.push_back(TargetVTs);
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001783 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1784 NumInputRootOpsCounts.push_back(NumInputRootOps);
Chris Lattner706d2d32006-08-09 16:44:44 +00001785 }
1786
Chris Lattner706d2d32006-08-09 16:44:44 +00001787 // Factor target node emission code (emitted by EmitResultCode) into
1788 // separate functions. Uniquing and share them among all instruction
1789 // selection routines.
1790 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1791 CodeList &GeneratedCode = CodeForPatterns[i].second;
1792 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1793 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001794 std::set<std::string> Decls = PatternDecls[i];
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001795 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1796 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001797 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001798 int CodeSize = (int)GeneratedCode.size();
1799 int LastPred = -1;
1800 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001801 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001802 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001803 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1804 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001805 }
1806
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001807 std::string CalleeCode = "(SDNode *N";
Evan Cheng9ade2182006-08-26 05:34:46 +00001808 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001809 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1810 CalleeCode += ", unsigned Opc" + utostr(j);
1811 CallerCode += ", " + TargetOpcodes[j];
1812 }
1813 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Anderson69110c92009-09-11 09:01:57 +00001814 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Chris Lattner706d2d32006-08-09 16:44:44 +00001815 CallerCode += ", " + TargetVTs[j];
1816 }
Evan Chengf5493192006-08-26 01:02:19 +00001817 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001818 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001819 std::string Name = *I;
Dan Gohman475871a2008-07-27 21:46:04 +00001820 CalleeCode += ", SDValue &" + Name;
Evan Cheng676d7312006-08-26 00:59:04 +00001821 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001822 }
Dan Gohmane4c67cd2008-05-31 02:11:25 +00001823
1824 if (OutputIsVariadic) {
1825 CalleeCode += ", unsigned NumInputRootOps";
1826 CallerCode += ", " + utostr(NumInputRootOps);
1827 }
1828
Chris Lattner706d2d32006-08-09 16:44:44 +00001829 CallerCode += ");";
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001830 CalleeCode += ") {\n";
Evan Cheng676d7312006-08-26 00:59:04 +00001831
1832 for (std::vector<std::string>::const_reverse_iterator
1833 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1834 CalleeCode += " " + *I + "\n";
1835
Evan Chengf5493192006-08-26 01:02:19 +00001836 for (int j = LastPred+1; j < CodeSize; ++j)
1837 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001838 for (int j = LastPred+1; j < CodeSize; ++j)
1839 GeneratedCode.pop_back();
1840 CalleeCode += "}\n";
1841
1842 // Uniquing the emission routines.
1843 unsigned EmitFuncNum;
1844 std::map<std::string, unsigned>::iterator EFI =
1845 EmitFunctions.find(CalleeCode);
1846 if (EFI != EmitFunctions.end()) {
1847 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001848 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001849 EmitFuncNum = EmitFunctions.size();
1850 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramerf2a39bd2009-11-14 16:37:18 +00001851 // Prevent emission routines from being inlined to reduce selection
1852 // routines stack frame sizes.
1853 OS << "DISABLE_INLINE ";
Evan Cheng06d64702006-08-11 08:59:35 +00001854 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001855 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001856
Chris Lattner706d2d32006-08-09 16:44:44 +00001857 // Replace the emission code within selection routines with calls to the
1858 // emission functions.
Chris Lattnera0cdf172010-02-13 20:06:50 +00001859 if (GenDebug)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001860 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001861 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1862 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1863 if (GenDebug) {
1864 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1865 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1866 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1867 GeneratedCode.push_back(std::make_pair(0, "}"));
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001868 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
David Greene8ad4c002008-10-27 21:56:29 +00001869 }
1870 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001871 }
1872
Chris Lattner706d2d32006-08-09 16:44:44 +00001873 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001874 std::string OpVTStr;
Owen Anderson825b72b2009-08-11 20:47:22 +00001875 if (OpVT == MVT::iPTR) {
Chris Lattner33a40042006-11-14 22:17:10 +00001876 OpVTStr = "_iPTR";
Owen Anderson825b72b2009-08-11 20:47:22 +00001877 } else if (OpVT == MVT::iPTRAny) {
Mon P Wange3b3a722008-07-30 04:36:53 +00001878 OpVTStr = "_iPTRAny";
Owen Anderson825b72b2009-08-11 20:47:22 +00001879 } else if (OpVT == MVT::isVoid) {
Chris Lattner33a40042006-11-14 22:17:10 +00001880 // Nodes with a void result actually have a first result type of either
1881 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1882 // void to this case, we handle it specially here.
1883 } else {
Owen Anderson825b72b2009-08-11 20:47:22 +00001884 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Chris Lattner33a40042006-11-14 22:17:10 +00001885 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001886 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1887 OpcodeVTMap.find(OpName);
1888 if (OpVTI == OpcodeVTMap.end()) {
1889 std::vector<std::string> VTSet;
1890 VTSet.push_back(OpVTStr);
1891 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1892 } else
1893 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001894
Dan Gohman0540e172008-10-15 06:17:21 +00001895 // We want to emit all of the matching code now. However, we want to emit
1896 // the matches in order of minimal cost. Sort the patterns so the least
1897 // cost one is at the start.
1898 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1899 PatternSortingPredicate(CGP));
1900
1901 // Scan the code to see if all of the patterns are reachable and if it is
1902 // possible that the last one might not match.
1903 bool mightNotMatch = true;
1904 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1905 CodeList &GeneratedCode = CodeForPatterns[i].second;
1906 mightNotMatch = false;
1907
1908 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1909 if (GeneratedCode[j].first == 1) { // predicate.
1910 mightNotMatch = true;
1911 break;
1912 }
1913 }
1914
1915 // If this pattern definitely matches, and if it isn't the last one, the
1916 // patterns after it CANNOT ever match. Error out.
1917 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbar1a551802009-07-03 00:10:29 +00001918 errs() << "Pattern '";
1919 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1920 errs() << "' is impossible to select!\n";
Dan Gohman0540e172008-10-15 06:17:21 +00001921 exit(1);
1922 }
1923 }
1924
Chris Lattner706d2d32006-08-09 16:44:44 +00001925 // Loop through and reverse all of the CodeList vectors, as we will be
1926 // accessing them from their logical front, but accessing the end of a
1927 // vector is more efficient.
1928 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1929 CodeList &GeneratedCode = CodeForPatterns[i].second;
1930 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001931 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001932
1933 // Next, reverse the list of patterns itself for the same reason.
1934 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1935
Dan Gohman63e3e632009-01-29 01:37:18 +00001936 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001937 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman63e3e632009-01-29 01:37:18 +00001938
Chris Lattner706d2d32006-08-09 16:44:44 +00001939 // Emit all of the patterns now, grouped together to share code.
1940 EmitPatterns(CodeForPatterns, 2, OS);
1941
Chris Lattner64906972006-09-21 18:28:27 +00001942 // If the last pattern has predicates (which could fail) emit code to
1943 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001944 if (mightNotMatch) {
Dan Gohman31bd42b2008-09-27 23:53:14 +00001945 OS << "\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00001946 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1947 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
Dan Gohman31bd42b2008-09-27 23:53:14 +00001948 OpName != "ISD::INTRINSIC_VOID")
1949 OS << " CannotYetSelect(N);\n";
1950 else
1951 OS << " CannotYetSelectIntrinsic(N);\n";
1952
1953 OS << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001954 }
1955 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001956 }
Chris Lattner602f6922006-01-04 00:25:00 +00001957 }
1958
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001959 OS << "// The main instruction selector code.\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001960 << "SDNode *SelectCode(SDNode *N) {\n"
1961 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1962 << " switch (N->getOpcode()) {\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001963 << " default:\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001964 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman28c04da2008-11-05 18:30:52 +00001965 << " break;\n"
1966 << " case ISD::EntryToken: // These nodes remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001967 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001968 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001969 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001970 << " case ISD::TargetConstant:\n"
Nate Begemane1795842008-02-14 08:57:00 +00001971 << " case ISD::TargetConstantFP:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001972 << " case ISD::TargetConstantPool:\n"
1973 << " case ISD::TargetFrameIndex:\n"
Bill Wendling056292f2008-09-16 21:48:12 +00001974 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman8c2b5252009-10-30 01:27:03 +00001975 << " case ISD::TargetBlockAddress:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001976 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001977 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohman8be6bbe2008-11-05 04:14:16 +00001978 << " case ISD::TargetGlobalAddress:\n"
1979 << " case ISD::TokenFactor:\n"
1980 << " case ISD::CopyFromReg:\n"
1981 << " case ISD::CopyToReg: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001982 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001983 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001984 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001985 << " case ISD::AssertZext: {\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00001986 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001987 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001988 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001989 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohmancd920d92008-07-02 23:23:19 +00001990 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Chengda47e6e2008-03-15 00:03:38 +00001991 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001992
Chris Lattner602f6922006-01-04 00:25:00 +00001993 // Loop over all of the case statements, emiting a call to each method we
1994 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001995 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001996 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1997 PBOI != E; ++PBOI) {
1998 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001999 // Potentially multiple versions of select for this opcode. One for each
2000 // ValueType of the node (or its first true operand if it doesn't produce a
2001 // result.
2002 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2003 OpcodeVTMap.find(OpName);
2004 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00002005 OS << " case " << OpName << ": {\n";
Dale Johannesen3b895cf2009-05-12 22:32:29 +00002006 // If we have only one variant and it's the default, elide the
2007 // switch. Marginally faster, and makes MSVC happier.
2008 if (OpVTs.size()==1 && OpVTs[0].empty()) {
2009 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2010 OS << " break;\n";
2011 OS << " }\n";
2012 continue;
2013 }
Evan Cheng425e8c72007-09-04 20:18:28 +00002014 // Keep track of whether we see a pattern that has an iPtr result.
2015 bool HasPtrPattern = false;
2016 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00002017
Evan Cheng425e8c72007-09-04 20:18:28 +00002018 OS << " switch (NVT) {\n";
2019 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2020 std::string &VTStr = OpVTs[i];
2021 if (VTStr.empty()) {
2022 HasDefaultPattern = true;
2023 continue;
2024 }
Chris Lattner717a6112006-11-14 21:50:27 +00002025
Evan Cheng425e8c72007-09-04 20:18:28 +00002026 // If this is a match on iPTR: don't emit it directly, we need special
2027 // code.
2028 if (VTStr == "_iPTR") {
2029 HasPtrPattern = true;
2030 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00002031 }
Owen Anderson825b72b2009-08-11 20:47:22 +00002032 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Cheng425e8c72007-09-04 20:18:28 +00002033 << " return Select_" << getLegalCName(OpName)
2034 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002035 }
Evan Cheng425e8c72007-09-04 20:18:28 +00002036 OS << " default:\n";
2037
2038 // If there is an iPTR result version of this pattern, emit it here.
2039 if (HasPtrPattern) {
Duncan Sands83ec4b62008-06-06 12:08:01 +00002040 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00002041 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2042 }
2043 if (HasDefaultPattern) {
2044 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2045 }
2046 OS << " break;\n";
2047 OS << " }\n";
2048 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002049 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00002050 }
Chris Lattner81303322005-09-23 19:36:15 +00002051
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002052 OS << " } // end of big switch.\n\n"
Dan Gohmaneeb3a002010-01-05 01:24:18 +00002053 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2054 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2055 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00002056 << " CannotYetSelect(N);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00002057 << " } else {\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00002058 << " CannotYetSelectIntrinsic(N);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00002059 << " }\n"
Dan Gohman31bd42b2008-09-27 23:53:14 +00002060 << " return NULL;\n"
2061 << "}\n\n";
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002062}
2063
Daniel Dunbar1a551802009-07-03 00:10:29 +00002064void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00002065 EmitSourceFileHeader("DAG Instruction Selector for the " +
2066 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002067
Chris Lattner1f39e292005-09-14 00:09:24 +00002068 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2069 << "// *** instruction selector class. These functions are really "
2070 << "methods.\n\n";
Chris Lattnerf8dc0612008-02-03 06:49:24 +00002071
Roman Levenstein6422e8a2008-05-14 10:17:11 +00002072 OS << "// Include standard, target-independent definitions and methods used\n"
2073 << "// by the instruction selector.\n";
Mike Stumpfe095f32009-05-04 18:40:41 +00002074 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00002075
Chris Lattner443e3f92008-01-05 22:54:53 +00002076 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00002077 EmitPredicateFunctions(OS);
2078
Chris Lattner569f1212009-08-23 04:44:11 +00002079 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerfe718932008-01-06 01:10:31 +00002080 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00002081 I != E; ++I) {
Chris Lattner569f1212009-08-23 04:44:11 +00002082 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
2083 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
2084 DEBUG(errs() << "\n");
Bill Wendlingf5da1332006-12-07 22:21:48 +00002085 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00002086
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002087 // At this point, we have full information about the 'Patterns' we need to
2088 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002089 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002090 EmitInstructionSelector(OS);
2091
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002092}