blob: 79d8e3d2dc9c272b3cc16163e5d8a6e0eb60b484 [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"
17#include "llvm/Support/Debug.h"
Chris Lattnerbe8e7212006-10-11 03:35:34 +000018#include "llvm/Support/MathExtras.h"
Bill Wendlingf5da1332006-12-07 22:21:48 +000019#include "llvm/Support/Streams.h"
Jeff Cohena48283b2005-09-25 19:04:43 +000020#include <algorithm>
Chris Lattner54cb8fd2005-09-07 23:44:43 +000021using namespace llvm;
22
Chris Lattnerca559d02005-09-08 21:03:01 +000023//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +000024// DAGISelEmitter Helper methods
Chris Lattner54cb8fd2005-09-07 23:44:43 +000025//
26
Chris Lattner6cefb772008-01-05 22:25:12 +000027/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
28/// ComplexPattern.
29static bool NodeIsComplexPattern(TreePatternNode *N) {
Evan Cheng0fc71982005-12-08 02:00:36 +000030 return (N->isLeaf() &&
31 dynamic_cast<DefInit*>(N->getLeafValue()) &&
32 static_cast<DefInit*>(N->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
34}
35
Chris Lattner6cefb772008-01-05 22:25:12 +000036/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Evan Cheng0fc71982005-12-08 02:00:36 +000038static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerfe718932008-01-06 01:10:31 +000039 CodeGenDAGPatterns &CGP) {
Evan Cheng0fc71982005-12-08 02:00:36 +000040 if (N->isLeaf() &&
41 dynamic_cast<DefInit*>(N->getLeafValue()) &&
42 static_cast<DefInit*>(N->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
Chris Lattner6cefb772008-01-05 22:25:12 +000044 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
45 ->getDef());
Evan Cheng0fc71982005-12-08 02:00:36 +000046 }
47 return NULL;
48}
49
Chris Lattner05814af2005-09-28 17:57:56 +000050/// getPatternSize - Return the 'size' of this pattern. We want to match large
51/// patterns before small ones. This is used to determine the size of a
52/// pattern.
Chris Lattnerfe718932008-01-06 01:10:31 +000053static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Chris Lattner6cefb772008-01-05 22:25:12 +000054 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Evan Cheng2618d072006-05-17 20:37:59 +000056 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR) &&
Evan Cheng4a7c2842006-01-06 22:19:44 +000059 "Not a valid pattern node to size!");
Evan Cheng6cec34e2006-09-08 07:26:39 +000060 unsigned Size = 3; // The node itself.
Evan Cheng657416c2006-02-01 06:06:31 +000061 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000064 Size += 2;
Evan Cheng0fc71982005-12-08 02:00:36 +000065
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner6cefb772008-01-05 22:25:12 +000071 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000072 if (AM)
Evan Cheng6cec34e2006-09-08 07:26:39 +000073 Size += AM->getNumOperands() * 3;
Chris Lattner3e179802006-02-03 18:06:02 +000074
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P->getPredicateFn().empty())
78 ++Size;
79
Chris Lattner05814af2005-09-28 17:57:56 +000080 // Count children in the count if they are also nodes.
81 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82 TreePatternNode *Child = P->getChild(i);
Nate Begemanb73628b2005-12-30 00:12:56 +000083 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner6cefb772008-01-05 22:25:12 +000084 Size += getPatternSize(Child, CGP);
Evan Cheng0fc71982005-12-08 02:00:36 +000085 else if (Child->isLeaf()) {
86 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
Evan Cheng6cec34e2006-09-08 07:26:39 +000087 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
Evan Cheng4a7c2842006-01-06 22:19:44 +000088 else if (NodeIsComplexPattern(Child))
Chris Lattner6cefb772008-01-05 22:25:12 +000089 Size += getPatternSize(Child, CGP);
Chris Lattner3e179802006-02-03 18:06:02 +000090 else if (!Child->getPredicateFn().empty())
91 ++Size;
Chris Lattner2f041d42005-10-19 04:41:05 +000092 }
Chris Lattner05814af2005-09-28 17:57:56 +000093 }
94
95 return Size;
96}
97
98/// getResultPatternCost - Compute the number of instructions for this pattern.
99/// This is a temporary hack. We should really include the instruction
100/// latencies in this calculation.
Chris Lattner6cefb772008-01-05 22:25:12 +0000101static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000102 CodeGenDAGPatterns &CGP) {
Chris Lattner05814af2005-09-28 17:57:56 +0000103 if (P->isLeaf()) return 0;
104
Evan Chengfbad7082006-02-18 02:33:09 +0000105 unsigned Cost = 0;
106 Record *Op = P->getOperator();
107 if (Op->isSubClassOf("Instruction")) {
108 Cost++;
Chris Lattner6cefb772008-01-05 22:25:12 +0000109 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Evan Chengfbad7082006-02-18 02:33:09 +0000110 if (II.usesCustomDAGSchedInserter)
111 Cost += 10;
112 }
Chris Lattner05814af2005-09-28 17:57:56 +0000113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000114 Cost += getResultPatternCost(P->getChild(i), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000115 return Cost;
116}
117
Evan Chenge6f32032006-07-19 00:24:41 +0000118/// getResultPatternCodeSize - Compute the code size of instructions for this
119/// pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000120static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerfe718932008-01-06 01:10:31 +0000121 CodeGenDAGPatterns &CGP) {
Evan Chenge6f32032006-07-19 00:24:41 +0000122 if (P->isLeaf()) return 0;
123
124 unsigned Cost = 0;
125 Record *Op = P->getOperator();
126 if (Op->isSubClassOf("Instruction")) {
127 Cost += Op->getValueAsInt("CodeSize");
128 }
129 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner6cefb772008-01-05 22:25:12 +0000130 Cost += getResultPatternSize(P->getChild(i), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000131 return Cost;
132}
133
Chris Lattner05814af2005-09-28 17:57:56 +0000134// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135// In particular, we want to match maximal patterns first and lowest cost within
136// a particular complexity first.
137struct PatternSortingPredicate {
Chris Lattnerfe718932008-01-06 01:10:31 +0000138 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139 CodeGenDAGPatterns &CGP;
Evan Cheng0fc71982005-12-08 02:00:36 +0000140
Chris Lattner60d81392008-01-05 22:30:17 +0000141 bool operator()(const PatternToMatch *LHS,
142 const PatternToMatch *RHS) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000143 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Evan Chengc81d2a02006-04-19 20:36:09 +0000145 LHSSize += LHS->getAddedComplexity();
146 RHSSize += RHS->getAddedComplexity();
Chris Lattner05814af2005-09-28 17:57:56 +0000147 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
148 if (LHSSize < RHSSize) return false;
149
150 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner6cefb772008-01-05 22:25:12 +0000151 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Evan Chenge6f32032006-07-19 00:24:41 +0000153 if (LHSCost < RHSCost) return true;
154 if (LHSCost > RHSCost) return false;
155
Chris Lattner6cefb772008-01-05 22:25:12 +0000156 return getResultPatternSize(LHS->getDstPattern(), CGP) <
157 getResultPatternSize(RHS->getDstPattern(), CGP);
Chris Lattner05814af2005-09-28 17:57:56 +0000158 }
159};
160
Nate Begeman6510b222005-12-01 04:51:06 +0000161/// getRegisterValueType - Look up and return the first ValueType of specified
162/// RegisterClass record
Evan Cheng66a48bb2005-12-01 00:18:45 +0000163static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Chris Lattner22faeab2005-12-05 02:36:37 +0000164 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165 return RC->getValueTypeNum(0);
Evan Cheng66a48bb2005-12-01 00:18:45 +0000166 return MVT::Other;
167}
168
Chris Lattner72fe91c2005-09-24 00:40:24 +0000169
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000170/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171/// type information from it.
172static void RemoveAllTypes(TreePatternNode *N) {
Nate Begemanb73628b2005-12-30 00:12:56 +0000173 N->removeTypes();
Chris Lattner0ee7cff2005-10-14 04:11:13 +0000174 if (!N->isLeaf())
175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176 RemoveAllTypes(N->getChild(i));
177}
Chris Lattner72fe91c2005-09-24 00:40:24 +0000178
Evan Cheng51fecc82006-01-09 18:27:06 +0000179/// NodeHasProperty - return true if TreePatternNode has the specified
180/// property.
Evan Cheng94b30402006-10-11 21:02:01 +0000181static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerfe718932008-01-06 01:10:31 +0000182 CodeGenDAGPatterns &CGP) {
Evan Cheng94b30402006-10-11 21:02:01 +0000183 if (N->isLeaf()) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000184 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Evan Cheng94b30402006-10-11 21:02:01 +0000185 if (CP)
186 return CP->hasProperty(Property);
187 return false;
188 }
Evan Cheng7b05bd52005-12-23 22:11:47 +0000189 Record *Operator = N->getOperator();
190 if (!Operator->isSubClassOf("SDNode")) return false;
191
Chris Lattner6cefb772008-01-05 22:25:12 +0000192 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Evan Cheng7b05bd52005-12-23 22:11:47 +0000193}
194
Evan Cheng94b30402006-10-11 21:02:01 +0000195static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerfe718932008-01-06 01:10:31 +0000196 CodeGenDAGPatterns &CGP) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000197 if (NodeHasProperty(N, Property, CGP))
Evan Cheng7b05bd52005-12-23 22:11:47 +0000198 return true;
Evan Cheng51fecc82006-01-09 18:27:06 +0000199
200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201 TreePatternNode *Child = N->getChild(i);
Chris Lattner6cefb772008-01-05 22:25:12 +0000202 if (PatternHasProperty(Child, Property, CGP))
Evan Cheng51fecc82006-01-09 18:27:06 +0000203 return true;
Evan Cheng7b05bd52005-12-23 22:11:47 +0000204 }
205
206 return false;
207}
208
Chris Lattnerdc32f982008-01-05 22:43:57 +0000209//===----------------------------------------------------------------------===//
Chris Lattner443e3f92008-01-05 22:54:53 +0000210// Node Transformation emitter implementation.
211//
212void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
214 // name.
Chris Lattnerfe718932008-01-06 01:10:31 +0000215 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner443e3f92008-01-05 22:54:53 +0000216 NXsByNameTy NXsByName;
217
Chris Lattnerfe718932008-01-06 01:10:31 +0000218 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner443e3f92008-01-05 22:54:53 +0000219 I != E; ++I)
220 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
221
222 OS << "\n// Node transformations.\n";
223
224 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
225 I != E; ++I) {
226 Record *SDNode = I->second.first;
227 std::string Code = I->second.second;
228
229 if (Code.empty()) continue; // Empty code? Skip it.
230
Chris Lattner200c57e2008-01-05 22:58:54 +0000231 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner443e3f92008-01-05 22:54:53 +0000232 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
233
234 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
235 << ") {\n";
236 if (ClassName != "SDNode")
237 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238 OS << Code << "\n}\n";
239 }
240}
241
242//===----------------------------------------------------------------------===//
Chris Lattnerdc32f982008-01-05 22:43:57 +0000243// Predicate emitter implementation.
244//
245
246void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247 OS << "\n// Predicate functions.\n";
248
249 // Walk the pattern fragments, adding them to a map, which sorts them by
250 // name.
251 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252 PFsByNameTy PFsByName;
253
Chris Lattnerfe718932008-01-06 01:10:31 +0000254 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000255 I != E; ++I)
256 PFsByName.insert(std::make_pair(I->first->getName(), *I));
257
258
259 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
260 I != E; ++I) {
261 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262 TreePattern *P = I->second.second;
263
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code = PatFragRecord->getValueAsCode("Predicate");
266 if (Code.empty()) continue;
267
268 if (P->getOnlyTree()->isLeaf())
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *N) {\n";
271 else {
272 std::string ClassName =
Chris Lattner200c57e2008-01-05 22:58:54 +0000273 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattnerdc32f982008-01-05 22:43:57 +0000274 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
275
276 OS << "inline bool Predicate_" << PatFragRecord->getName()
277 << "(SDNode *" << C2 << ") {\n";
278 if (ClassName != "SDNode")
279 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
280 }
281 OS << Code << "\n}\n";
282 }
283
284 OS << "\n\n";
285}
286
287
288//===----------------------------------------------------------------------===//
289// PatternCodeEmitter implementation.
290//
Evan Chengb915f312005-12-09 22:45:35 +0000291class PatternCodeEmitter {
292private:
Chris Lattnerfe718932008-01-06 01:10:31 +0000293 CodeGenDAGPatterns &CGP;
Evan Chengb915f312005-12-09 22:45:35 +0000294
Evan Cheng58e84a62005-12-14 22:02:59 +0000295 // Predicates.
296 ListInit *Predicates;
Evan Cheng59413202006-04-19 18:07:24 +0000297 // Pattern cost.
298 unsigned Cost;
Evan Cheng58e84a62005-12-14 22:02:59 +0000299 // Instruction selector pattern.
300 TreePatternNode *Pattern;
301 // Matched instruction.
302 TreePatternNode *Instruction;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000303
Evan Chengb915f312005-12-09 22:45:35 +0000304 // Node to name mapping
Evan Chengf805c2e2006-01-12 19:35:54 +0000305 std::map<std::string, std::string> VariableMap;
306 // Node to operator mapping
307 std::map<std::string, Record*> OperatorMap;
Evan Chengb915f312005-12-09 22:45:35 +0000308 // Names of all the folded nodes which produce chains.
Evan Cheng1b80f4d2005-12-19 07:18:51 +0000309 std::vector<std::pair<std::string, unsigned> > FoldedChains;
Evan Cheng4326ef52006-10-12 02:08:53 +0000310 // Original input chain(s).
311 std::vector<std::pair<std::string, std::string> > OrigChains;
Evan Chengb4ad33c2006-01-19 01:55:45 +0000312 std::set<std::string> Duplicates;
Evan Chengb915f312005-12-09 22:45:35 +0000313
Evan Cheng676d7312006-08-26 00:59:04 +0000314 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000315 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000316 /// tested, and if true, the match fails) [when 1], or normal code to emit
317 /// [when 0], or initialization code to emit [when 2].
318 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +0000319 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
320 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000321 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000322 /// TargetOpcodes - The target specific opcodes used by the resulting
323 /// instructions.
324 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000325 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000326
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000327 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000328 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000329 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000330 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000331
332 void emitCheck(const std::string &S) {
333 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000334 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000335 }
336 void emitCode(const std::string &S) {
337 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000338 GeneratedCode.push_back(std::make_pair(0, S));
339 }
340 void emitInit(const std::string &S) {
341 if (!S.empty())
342 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000343 }
Evan Chengf5493192006-08-26 01:02:19 +0000344 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000345 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000346 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000347 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000348 void emitOpcode(const std::string &Opc) {
349 TargetOpcodes.push_back(Opc);
350 OpcNo++;
351 }
Evan Chengf8729402006-07-16 06:12:52 +0000352 void emitVT(const std::string &VT) {
353 TargetVTs.push_back(VT);
354 VTNo++;
355 }
Evan Chengb915f312005-12-09 22:45:35 +0000356public:
Chris Lattnerfe718932008-01-06 01:10:31 +0000357 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
Evan Cheng58e84a62005-12-14 22:02:59 +0000358 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000359 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000360 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000361 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +0000362 std::vector<std::string> &tv)
Chris Lattner6cefb772008-01-05 22:25:12 +0000363 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000364 GeneratedCode(gc), GeneratedDecl(gd),
365 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +0000366 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000367
368 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
369 /// if the match fails. At this point, we already know that the opcode for N
370 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000371 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
372 const std::string &RootName, const std::string &ChainSuffix,
373 bool &FoundChain) {
Evan Chenge41bf822006-02-05 06:43:12 +0000374 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +0000375 // Emit instruction predicates. Each predicate is just a string for now.
376 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000377 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +0000378 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
379 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
380 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +0000381 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000382#ifndef NDEBUG
383 Def->dump();
384#endif
Evan Cheng58e84a62005-12-14 22:02:59 +0000385 assert(0 && "Unknown predicate type!");
386 }
Chris Lattner8a0604b2006-01-28 20:31:24 +0000387 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +0000388 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +0000389 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +0000390 }
391 }
Chris Lattner8a0604b2006-01-28 20:31:24 +0000392
393 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +0000394 }
395
Evan Chengb915f312005-12-09 22:45:35 +0000396 if (N->isLeaf()) {
397 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000398 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +0000399 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +0000400 return;
401 } else if (!NodeIsComplexPattern(N)) {
402 assert(0 && "Cannot match this as a leaf value!");
403 abort();
404 }
405 }
406
Chris Lattner488580c2006-01-28 19:06:51 +0000407 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +0000408 // we already saw this in the pattern, emit code to verify dagness.
409 if (!N->getName().empty()) {
410 std::string &VarMapEntry = VariableMap[N->getName()];
411 if (VarMapEntry.empty()) {
412 VarMapEntry = RootName;
413 } else {
414 // If we get here, this is a second reference to a specific name. Since
415 // we already have checked that the first reference is valid, we don't
416 // have to recursively match it, just check that it's the same as the
417 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +0000418 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +0000419 return;
420 }
Evan Chengf805c2e2006-01-12 19:35:54 +0000421
422 if (!N->isLeaf())
423 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +0000424 }
425
426
427 // Emit code to load the child nodes and match their contents recursively.
428 unsigned OpNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000429 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
430 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Evan Cheng1feeeec2006-01-26 19:13:45 +0000431 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +0000432 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +0000433 if (NodeHasChain)
434 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +0000435 if (!isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000436 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +0000437 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +0000438 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +0000439 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +0000440 // If the immediate use can somehow reach this node through another
441 // path, then can't fold it either or it will create a cycle.
442 // e.g. In the following diagram, XX can reach ld through YY. If
443 // ld is folded into XX, then YY is both a predecessor and a successor
444 // of XX.
445 //
446 // [ld]
447 // ^ ^
448 // | |
449 // / \---
450 // / [YY]
451 // | ^
452 // [XX]-------|
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000453 bool NeedCheck = false;
454 if (P != Pattern)
455 NeedCheck = true;
456 else {
Chris Lattner6cefb772008-01-05 22:25:12 +0000457 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000458 NeedCheck =
Chris Lattner6cefb772008-01-05 22:25:12 +0000459 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
460 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
461 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Evan Chengce1381a2006-10-14 08:30:15 +0000462 PInfo.getNumOperands() > 1 ||
Evan Cheng94b30402006-10-11 21:02:01 +0000463 PInfo.hasProperty(SDNPHasChain) ||
464 PInfo.hasProperty(SDNPInFlag) ||
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000465 PInfo.hasProperty(SDNPOptInFlag);
466 }
467
468 if (NeedCheck) {
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000469 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner706d2d32006-08-09 16:44:44 +0000470 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
Evan Chengce1381a2006-10-14 08:30:15 +0000471 ".Val, N.Val)");
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000472 }
Evan Chenge41bf822006-02-05 06:43:12 +0000473 }
Evan Chengb915f312005-12-09 22:45:35 +0000474 }
Evan Chenge41bf822006-02-05 06:43:12 +0000475
Evan Chengc15d18c2006-01-27 22:13:45 +0000476 if (NodeHasChain) {
Evan Cheng4326ef52006-10-12 02:08:53 +0000477 if (FoundChain) {
478 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
479 "IsChainCompatible(" + ChainName + ".Val, " +
480 RootName + ".Val))");
481 OrigChains.push_back(std::make_pair(ChainName, RootName));
482 } else
Evan Chenge6389932006-07-21 22:19:51 +0000483 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000484 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +0000485 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +0000486 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +0000487 }
Evan Chengb915f312005-12-09 22:45:35 +0000488 }
489
Evan Cheng54597732006-01-26 00:22:25 +0000490 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +0000491 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +0000492 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +0000493 // FIXME: If the optional incoming flag does not exist. Then it is ok to
494 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +0000495 if (!isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000496 (PatternHasProperty(N, SDNPInFlag, CGP) ||
497 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
498 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +0000499 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000500 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +0000501 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +0000502 }
503 }
504
Evan Chengd3eea902006-10-09 21:02:17 +0000505 // If there is a node predicate for this, emit the call.
506 if (!N->getPredicateFn().empty())
507 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
508
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000509
Chris Lattner39e73f72006-10-11 04:05:55 +0000510 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
511 // a constant without a predicate fn that has more that one bit set, handle
512 // this as a special case. This is usually for targets that have special
513 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
514 // handling stuff). Using these instructions is often far more efficient
515 // than materializing the constant. Unfortunately, both the instcombiner
516 // and the dag combiner can often infer that bits are dead, and thus drop
517 // them from the mask in the dag. For example, it might turn 'AND X, 255'
518 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
519 // to handle this.
520 if (!N->isLeaf() &&
521 (N->getOperator()->getName() == "and" ||
522 N->getOperator()->getName() == "or") &&
523 N->getChild(1)->isLeaf() &&
524 N->getChild(1)->getPredicateFn().empty()) {
525 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
526 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
527 emitInit("SDOperand " + RootName + "0" + " = " +
528 RootName + ".getOperand(" + utostr(0) + ");");
529 emitInit("SDOperand " + RootName + "1" + " = " +
530 RootName + ".getOperand(" + utostr(1) + ");");
531
532 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
533 const char *MaskPredicate = N->getOperator()->getName() == "or"
534 ? "CheckOrMask(" : "CheckAndMask(";
535 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
536 RootName + "1), " + itostr(II->getValue()) + ")");
537
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000538 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
Chris Lattner39e73f72006-10-11 04:05:55 +0000539 ChainSuffix + utostr(0), FoundChain);
540 return;
541 }
542 }
543 }
544
Evan Chengb915f312005-12-09 22:45:35 +0000545 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +0000546 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000547 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000548
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000549 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000550 ChainSuffix + utostr(OpNo), FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000551 }
552
Evan Cheng676d7312006-08-26 00:59:04 +0000553 // Handle cases when root is a complex pattern.
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000554 const ComplexPattern *CP;
Chris Lattner6cefb772008-01-05 22:25:12 +0000555 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Evan Cheng676d7312006-08-26 00:59:04 +0000556 std::string Fn = CP->getSelectFunc();
557 unsigned NumOps = CP->getNumOperands();
558 for (unsigned i = 0; i < NumOps; ++i) {
559 emitDecl("CPTmp" + utostr(i));
560 emitCode("SDOperand CPTmp" + utostr(i) + ";");
561 }
Evan Cheng94b30402006-10-11 21:02:01 +0000562 if (CP->hasProperty(SDNPHasChain)) {
563 emitDecl("CPInChain");
564 emitDecl("Chain" + ChainSuffix);
565 emitCode("SDOperand CPInChain;");
566 emitCode("SDOperand Chain" + ChainSuffix + ";");
567 }
Evan Cheng676d7312006-08-26 00:59:04 +0000568
Evan Cheng811731e2006-11-08 20:31:10 +0000569 std::string Code = Fn + "(" + RootName + ", " + RootName;
Evan Cheng676d7312006-08-26 00:59:04 +0000570 for (unsigned i = 0; i < NumOps; i++)
571 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +0000572 if (CP->hasProperty(SDNPHasChain)) {
573 ChainName = "Chain" + ChainSuffix;
574 Code += ", CPInChain, Chain" + ChainSuffix;
575 }
Evan Cheng676d7312006-08-26 00:59:04 +0000576 emitCheck(Code + ")");
577 }
Evan Chengb915f312005-12-09 22:45:35 +0000578 }
Chris Lattner39e73f72006-10-11 04:05:55 +0000579
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000580 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
581 const std::string &RootName,
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000582 const std::string &ChainSuffix, bool &FoundChain) {
583 if (!Child->isLeaf()) {
584 // If it's not a leaf, recursively match.
Chris Lattner6cefb772008-01-05 22:25:12 +0000585 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000586 emitCheck(RootName + ".getOpcode() == " +
587 CInfo.getEnumName());
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000588 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Chris Lattner6cefb772008-01-05 22:25:12 +0000589 if (NodeHasProperty(Child, SDNPHasChain, CGP))
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000590 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
591 } else {
592 // If this child has a name associated with it, capture it in VarMap. If
593 // we already saw this in the pattern, emit code to verify dagness.
594 if (!Child->getName().empty()) {
595 std::string &VarMapEntry = VariableMap[Child->getName()];
596 if (VarMapEntry.empty()) {
597 VarMapEntry = RootName;
598 } else {
599 // If we get here, this is a second reference to a specific name.
600 // Since we already have checked that the first reference is valid,
601 // we don't have to recursively match it, just check that it's the
602 // same as the previously named thing.
603 emitCheck(VarMapEntry + " == " + RootName);
604 Duplicates.insert(RootName);
605 return;
606 }
607 }
608
609 // Handle leaves of various types.
610 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
611 Record *LeafRec = DI->getDef();
Chris Lattner646085d2006-11-14 21:18:40 +0000612 if (LeafRec->isSubClassOf("RegisterClass") ||
613 LeafRec->getName() == "ptr_rc") {
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000614 // Handle register references. Nothing to do here.
615 } else if (LeafRec->isSubClassOf("Register")) {
616 // Handle register references.
617 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
618 // Handle complex pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000619 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000620 std::string Fn = CP->getSelectFunc();
621 unsigned NumOps = CP->getNumOperands();
622 for (unsigned i = 0; i < NumOps; ++i) {
623 emitDecl("CPTmp" + utostr(i));
624 emitCode("SDOperand CPTmp" + utostr(i) + ";");
625 }
Evan Cheng94b30402006-10-11 21:02:01 +0000626 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000627 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Evan Cheng94b30402006-10-11 21:02:01 +0000628 FoldedChains.push_back(std::make_pair("CPInChain",
629 PInfo.getNumResults()));
630 ChainName = "Chain" + ChainSuffix;
631 emitDecl("CPInChain");
632 emitDecl(ChainName);
633 emitCode("SDOperand CPInChain;");
634 emitCode("SDOperand " + ChainName + ";");
635 }
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000636
Evan Cheng811731e2006-11-08 20:31:10 +0000637 std::string Code = Fn + "(N, ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000638 if (CP->hasProperty(SDNPHasChain)) {
639 std::string ParentName(RootName.begin(), RootName.end()-1);
Evan Cheng811731e2006-11-08 20:31:10 +0000640 Code += ParentName + ", ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000641 }
642 Code += RootName;
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000643 for (unsigned i = 0; i < NumOps; i++)
644 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +0000645 if (CP->hasProperty(SDNPHasChain))
646 Code += ", CPInChain, Chain" + ChainSuffix;
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000647 emitCheck(Code + ")");
648 } else if (LeafRec->getName() == "srcvalue") {
649 // Place holder for SRCVALUE nodes. Nothing to do here.
650 } else if (LeafRec->isSubClassOf("ValueType")) {
651 // Make sure this is the specified value type.
652 emitCheck("cast<VTSDNode>(" + RootName +
653 ")->getVT() == MVT::" + LeafRec->getName());
654 } else if (LeafRec->isSubClassOf("CondCode")) {
655 // Make sure this is the specified cond code.
656 emitCheck("cast<CondCodeSDNode>(" + RootName +
657 ")->get() == ISD::" + LeafRec->getName());
658 } else {
659#ifndef NDEBUG
660 Child->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +0000661 cerr << " ";
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000662#endif
663 assert(0 && "Unknown leaf type!");
664 }
665
666 // If there is a node predicate for this, emit the call.
667 if (!Child->getPredicateFn().empty())
668 emitCheck(Child->getPredicateFn() + "(" + RootName +
669 ".Val)");
670 } else if (IntInit *II =
671 dynamic_cast<IntInit*>(Child->getLeafValue())) {
672 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
673 unsigned CTmp = TmpNo++;
674 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
675 RootName + ")->getSignExtended();");
676
677 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
678 } else {
679#ifndef NDEBUG
680 Child->dump();
681#endif
682 assert(0 && "Unknown leaf type!");
683 }
684 }
685 }
Evan Chengb915f312005-12-09 22:45:35 +0000686
687 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
688 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000689 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000690 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000691 bool InFlagDecled, bool ResNodeDecled,
692 bool LikeLeaf = false, bool isRoot = false) {
693 // List of arguments of getTargetNode() or SelectNodeTo().
694 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000695 // This is something selected from the pattern we matched.
696 if (!N->getName().empty()) {
Scott Michel6be48d42008-01-29 02:29:31 +0000697 const std::string &VarName = N->getName();
698 std::string Val = VariableMap[VarName];
699 bool ModifiedVal = false;
Evan Chengb915f312005-12-09 22:45:35 +0000700 assert(!Val.empty() &&
701 "Variable referenced but not defined and not caught earlier!");
702 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
703 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +0000704 NodeOps.push_back(Val);
705 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000706 }
707
708 const ComplexPattern *CP;
709 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +0000710 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +0000711 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +0000712 std::string CastType;
Scott Michel6be48d42008-01-29 02:29:31 +0000713 std::string TmpVar = "Tmp" + utostr(ResNo);
Nate Begemanb73628b2005-12-30 00:12:56 +0000714 switch (N->getTypeNum(0)) {
Chris Lattnerd8a17282007-01-17 07:45:12 +0000715 default:
716 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
717 << " type as an immediate constant. Aborting\n";
718 abort();
Chris Lattner78593132006-01-29 20:01:35 +0000719 case MVT::i1: CastType = "bool"; break;
720 case MVT::i8: CastType = "unsigned char"; break;
721 case MVT::i16: CastType = "unsigned short"; break;
722 case MVT::i32: CastType = "unsigned"; break;
723 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +0000724 }
Scott Michel6be48d42008-01-29 02:29:31 +0000725 emitCode("SDOperand " + TmpVar +
Evan Chengfceb57a2006-07-15 08:45:20 +0000726 " = CurDAG->getTargetConstant(((" + CastType +
727 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
728 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000729 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
730 // value if used multiple times by this pattern result.
Scott Michel6be48d42008-01-29 02:29:31 +0000731 Val = TmpVar;
732 ModifiedVal = true;
733 NodeOps.push_back(Val);
Evan Chengbb48e332006-01-12 07:54:57 +0000734 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +0000735 Record *Op = OperatorMap[N->getName()];
736 // Transform ExternalSymbol to TargetExternalSymbol
737 if (Op && Op->getName() == "externalsym") {
Scott Michel6be48d42008-01-29 02:29:31 +0000738 std::string TmpVar = "Tmp"+utostr(ResNo);
739 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +0000740 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +0000741 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000742 getEnumName(N->getTypeNum(0)) + ");");
Chris Lattner64906972006-09-21 18:28:27 +0000743 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
744 // this value if used multiple times by this pattern result.
Scott Michel6be48d42008-01-29 02:29:31 +0000745 Val = TmpVar;
746 ModifiedVal = true;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000747 }
Scott Michel6be48d42008-01-29 02:29:31 +0000748 NodeOps.push_back(Val);
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +0000749 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
750 || N->getOperator()->getName() == "tglobaltlsaddr")) {
Evan Chengf805c2e2006-01-12 19:35:54 +0000751 Record *Op = OperatorMap[N->getName()];
752 // Transform GlobalAddress to TargetGlobalAddress
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +0000753 if (Op && (Op->getName() == "globaladdr" ||
754 Op->getName() == "globaltlsaddr")) {
Scott Michel6be48d42008-01-29 02:29:31 +0000755 std::string TmpVar = "Tmp" + utostr(ResNo);
756 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +0000757 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +0000758 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000759 ");");
Chris Lattner64906972006-09-21 18:28:27 +0000760 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
761 // this value if used multiple times by this pattern result.
Scott Michel6be48d42008-01-29 02:29:31 +0000762 Val = TmpVar;
763 ModifiedVal = true;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000764 }
Evan Cheng676d7312006-08-26 00:59:04 +0000765 NodeOps.push_back(Val);
Scott Michel6be48d42008-01-29 02:29:31 +0000766 } else if (!N->isLeaf()
767 && (N->getOperator()->getName() == "texternalsym"
768 || N->getOperator()->getName() == "tconstpool")) {
769 // Do not rewrite the variable name, since we don't generate a new
770 // temporary.
Evan Cheng676d7312006-08-26 00:59:04 +0000771 NodeOps.push_back(Val);
Chris Lattner6cefb772008-01-05 22:25:12 +0000772 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Evan Cheng676d7312006-08-26 00:59:04 +0000773 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
774 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
775 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +0000776 }
Evan Chengb915f312005-12-09 22:45:35 +0000777 } else {
Evan Cheng676d7312006-08-26 00:59:04 +0000778 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +0000779 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +0000780 if (!LikeLeaf) {
781 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +0000782 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000783 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +0000784 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +0000785 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +0000786 }
Evan Cheng676d7312006-08-26 00:59:04 +0000787 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +0000788 }
Scott Michel6be48d42008-01-29 02:29:31 +0000789
790 if (ModifiedVal) {
791 VariableMap[VarName] = Val;
792 }
Evan Cheng676d7312006-08-26 00:59:04 +0000793 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000794 }
Evan Chengb915f312005-12-09 22:45:35 +0000795 if (N->isLeaf()) {
796 // If this is an explicit register reference, handle it.
797 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
798 unsigned ResNo = TmpNo++;
799 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +0000800 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000801 getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000802 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000803 NodeOps.push_back("Tmp" + utostr(ResNo));
804 return NodeOps;
Evan Cheng7774be42007-07-05 07:19:45 +0000805 } else if (DI->getDef()->getName() == "zero_reg") {
806 emitCode("SDOperand Tmp" + utostr(ResNo) +
807 " = CurDAG->getRegister(0, " +
808 getEnumName(N->getTypeNum(0)) + ");");
809 NodeOps.push_back("Tmp" + utostr(ResNo));
810 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000811 }
812 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
813 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +0000814 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +0000815 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000816 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +0000817 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000818 NodeOps.push_back("Tmp" + utostr(ResNo));
819 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000820 }
821
Jim Laskey16d42c62006-07-11 18:25:13 +0000822#ifndef NDEBUG
823 N->dump();
824#endif
Evan Chengb915f312005-12-09 22:45:35 +0000825 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +0000826 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000827 }
828
829 Record *Op = N->getOperator();
830 if (Op->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000831 const CodeGenTarget &CGT = CGP.getTargetInfo();
Evan Cheng7b05bd52005-12-23 22:11:47 +0000832 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +0000833 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattnerf1ab4f12008-01-06 01:52:22 +0000834 const TreePattern *InstPat = Inst.getPattern();
Evan Chengd23aa5a2007-09-25 01:48:59 +0000835 // FIXME: Assume actual pattern comes before "implicit".
Evan Cheng045953c2006-05-10 00:05:46 +0000836 TreePatternNode *InstPatNode =
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000837 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
838 : (InstPat ? InstPat->getTree(0) : NULL);
Evan Cheng045953c2006-05-10 00:05:46 +0000839 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengaeb7d4d2007-09-11 19:52:18 +0000840 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Evan Cheng045953c2006-05-10 00:05:46 +0000841 }
Chris Lattner8f707e12008-01-07 05:19:29 +0000842 bool HasVarOps = isRoot && II.isVariadic;
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000843 // FIXME: fix how we deal with physical register operands.
Evan Cheng045953c2006-05-10 00:05:46 +0000844 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000845 bool HasImpResults = isRoot && DstRegs.size() > 0;
Evan Cheng045953c2006-05-10 00:05:46 +0000846 bool NodeHasOptInFlag = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000847 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Evan Cheng045953c2006-05-10 00:05:46 +0000848 bool NodeHasInFlag = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000849 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengef61ed32007-09-07 23:59:02 +0000850 bool NodeHasOutFlag = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000851 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Evan Cheng045953c2006-05-10 00:05:46 +0000852 bool NodeHasChain = InstPatNode &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000853 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Evan Cheng3eff89b2006-05-10 02:47:57 +0000854 bool InputHasChain = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000855 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000856 unsigned NumResults = Inst.getNumResults();
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000857 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Evan Cheng4fba2812005-12-20 07:37:41 +0000858
Evan Chengfceb57a2006-07-15 08:45:20 +0000859 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000860 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +0000861 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +0000862 }
Evan Chenge945f4d2006-06-14 22:22:20 +0000863 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +0000864 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +0000865
Evan Cheng823b7522006-01-19 21:57:10 +0000866 // How many results is this pattern expected to produce?
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000867 unsigned NumPatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +0000868 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
869 MVT::ValueType VT = Pattern->getTypeNum(i);
870 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000871 NumPatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +0000872 }
873
Evan Cheng4326ef52006-10-12 02:08:53 +0000874 if (OrigChains.size() > 0) {
875 // The original input chain is being ignored. If it is not just
876 // pointing to the op that's being folded, we should create a
877 // TokenFactor with it and the chain of the folded op as the new chain.
878 // We could potentially be doing multiple levels of folding, in that
879 // case, the TokenFactor can have more operands.
880 emitCode("SmallVector<SDOperand, 8> InChains;");
881 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
882 emitCode("if (" + OrigChains[i].first + ".Val != " +
883 OrigChains[i].second + ".Val) {");
884 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
885 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
886 emitCode("}");
887 }
888 emitCode("AddToISelQueue(" + ChainName + ");");
889 emitCode("InChains.push_back(" + ChainName + ");");
890 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
891 "&InChains[0], InChains.size());");
892 }
893
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000894 // Loop over all of the operands of the instruction pattern, emitting code
895 // to fill them all in. The node 'N' usually has number children equal to
896 // the number of input operands of the instruction. However, in cases
897 // where there are predicate operands for an instruction, we need to fill
898 // in the 'execute always' values. Match up the node operands to the
899 // instruction operands to do this.
Evan Cheng676d7312006-08-26 00:59:04 +0000900 std::vector<std::string> AllOps;
Evan Cheng39376d02007-05-15 01:19:51 +0000901 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000902 for (unsigned ChildNo = 0, InstOpNo = NumResults;
903 InstOpNo != II.OperandList.size(); ++InstOpNo) {
904 std::vector<std::string> Ops;
905
Evan Cheng59039632007-05-08 21:04:07 +0000906 // If this is a normal operand or a predicate operand without
907 // 'execute always', emit it.
908 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Evan Chenga9559392007-07-06 01:05:26 +0000909 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
910 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000911 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Evan Cheng30729b42007-09-17 22:26:41 +0000912 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000913 InFlagDecled, ResNodeDecled);
914 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
915 ++ChildNo;
916 } else {
Evan Chenga9559392007-07-06 01:05:26 +0000917 // Otherwise, this is a predicate or optional def operand, emit the
918 // 'default ops' operands.
919 const DAGDefaultOperand &DefaultOp =
Chris Lattner6cefb772008-01-05 22:25:12 +0000920 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Evan Chenga9559392007-07-06 01:05:26 +0000921 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Cheng30729b42007-09-17 22:26:41 +0000922 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000923 InFlagDecled, ResNodeDecled);
924 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Evan Cheng39376d02007-05-15 01:19:51 +0000925 NumEAInputs += Ops.size();
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000926 }
927 }
Evan Chengb915f312005-12-09 22:45:35 +0000928 }
929
Evan Chengb915f312005-12-09 22:45:35 +0000930 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +0000931 bool ChainEmitted = NodeHasChain;
932 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +0000933 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +0000934 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +0000935 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
936 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +0000937 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +0000938 if (!InFlagDecled) {
939 emitCode("SDOperand InFlag(0, 0);");
940 InFlagDecled = true;
941 }
Evan Chengf037ca62006-08-27 08:11:28 +0000942 if (NodeHasOptInFlag) {
943 emitCode("if (HasInFlag) {");
944 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
945 emitCode(" AddToISelQueue(InFlag);");
946 emitCode("}");
947 }
Evan Chengbc6b86a2006-06-14 19:27:50 +0000948 }
Evan Chengb915f312005-12-09 22:45:35 +0000949
Evan Chengb915f312005-12-09 22:45:35 +0000950 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +0000951 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
Evan Chengef61ed32007-09-07 23:59:02 +0000952 NodeHasOptInFlag || HasImpResults) {
Evan Chenge945f4d2006-06-14 22:22:20 +0000953 std::string Code;
954 std::string Code2;
955 std::string NodeName;
956 if (!isRoot) {
957 NodeName = "Tmp" + utostr(ResNo);
Dan Gohmana6a1ab32007-07-24 22:58:00 +0000958 Code2 = "SDOperand " + NodeName + "(";
Evan Cheng9789aaa2006-01-24 20:46:50 +0000959 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +0000960 NodeName = "ResNode";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +0000961 if (!ResNodeDecled) {
Evan Cheng676d7312006-08-26 00:59:04 +0000962 Code2 = "SDNode *" + NodeName + " = ";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +0000963 ResNodeDecled = true;
964 } else
Evan Cheng676d7312006-08-26 00:59:04 +0000965 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +0000966 }
Evan Chengf037ca62006-08-27 08:11:28 +0000967
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000968 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +0000969 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000970 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +0000971
972 // Output order: results, chain, flags
973 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +0000974 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
975 Code += ", VT" + utostr(VTNo);
976 emitVT(getEnumName(N->getTypeNum(0)));
977 }
Evan Chengef61ed32007-09-07 23:59:02 +0000978 // Add types for implicit results in physical registers, scheduler will
979 // care of adding copyfromreg nodes.
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000980 for (unsigned i = 0; i < NumDstRegs; i++) {
981 Record *RR = DstRegs[i];
982 if (RR->isSubClassOf("Register")) {
983 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
984 Code += ", " + getEnumName(RVT);
Evan Chengef61ed32007-09-07 23:59:02 +0000985 }
986 }
Evan Chenge945f4d2006-06-14 22:22:20 +0000987 if (NodeHasChain)
988 Code += ", MVT::Other";
989 if (NodeHasOutFlag)
990 Code += ", MVT::Flag";
991
Chris Lattner7c3a96b2006-11-14 18:41:38 +0000992 // Figure out how many fixed inputs the node has. This is important to
993 // know which inputs are the variable ones if present.
994 unsigned NumInputs = AllOps.size();
995 NumInputs += NodeHasChain;
996
Evan Chenge945f4d2006-06-14 22:22:20 +0000997 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +0000998 if (HasVarOps) {
999 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1000 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1001 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00001002 }
1003
1004 if (HasVarOps) {
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001005 // Figure out whether any operands at the end of the op list are not
1006 // part of the variable section.
1007 std::string EndAdjust;
Evan Chenge945f4d2006-06-14 22:22:20 +00001008 if (NodeHasInFlag || HasImpInputs)
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001009 EndAdjust = "-1"; // Always has one flag.
1010 else if (NodeHasOptInFlag)
1011 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1012
Evan Cheng39376d02007-05-15 01:19:51 +00001013 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001014 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1015
Evan Cheng676d7312006-08-26 00:59:04 +00001016 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00001017 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00001018 emitCode("}");
1019 }
1020
1021 if (NodeHasChain) {
1022 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00001023 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00001024 else
Evan Chengf037ca62006-08-27 08:11:28 +00001025 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00001026 }
1027
Evan Chengf037ca62006-08-27 08:11:28 +00001028 if (HasVarOps) {
1029 if (NodeHasInFlag || HasImpInputs)
1030 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1031 else if (NodeHasOptInFlag) {
1032 emitCode("if (HasInFlag)");
1033 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1034 }
1035 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1036 ".size()";
1037 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001038 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00001039
Evan Chengf037ca62006-08-27 08:11:28 +00001040 unsigned NumOps = AllOps.size();
1041 if (NumOps) {
1042 if (!NodeHasOptInFlag && NumOps < 4) {
1043 for (unsigned i = 0; i != NumOps; ++i)
1044 Code += ", " + AllOps[i];
1045 } else {
1046 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1047 for (unsigned i = 0; i != NumOps; ++i) {
1048 OpsCode += AllOps[i];
1049 if (i != NumOps-1)
1050 OpsCode += ", ";
1051 }
1052 emitCode(OpsCode + " };");
1053 Code += ", Ops" + utostr(OpsNo) + ", ";
1054 if (NodeHasOptInFlag) {
1055 Code += "HasInFlag ? ";
1056 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1057 } else
1058 Code += utostr(NumOps);
1059 }
1060 }
1061
Evan Chenge945f4d2006-06-14 22:22:20 +00001062 if (!isRoot)
1063 Code += "), 0";
1064 emitCode(Code2 + Code + ");");
1065
1066 if (NodeHasChain)
1067 // Remember which op produces the chain.
1068 if (!isRoot)
1069 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001070 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00001071 else
1072 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001073 ", " + utostr(NumResults+NumDstRegs) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001074
Evan Cheng676d7312006-08-26 00:59:04 +00001075 if (!isRoot) {
1076 NodeOps.push_back("Tmp" + utostr(ResNo));
1077 return NodeOps;
1078 }
Evan Cheng045953c2006-05-10 00:05:46 +00001079
Evan Cheng06d64702006-08-11 08:59:35 +00001080 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00001081 if (NodeHasOutFlag) {
1082 if (!InFlagDecled) {
Dan Gohmana6a1ab32007-07-24 22:58:00 +00001083 emitCode("SDOperand InFlag(ResNode, " +
Evan Cheng30729b42007-09-17 22:26:41 +00001084 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00001085 InFlagDecled = true;
1086 } else
1087 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng30729b42007-09-17 22:26:41 +00001088 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00001089 }
Evan Cheng4fba2812005-12-20 07:37:41 +00001090
Evan Cheng97938882005-12-22 02:24:50 +00001091 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001092 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001093 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00001094 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00001095 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00001096 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001097 utostr(NumResults+NumDstRegs) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00001098 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00001099 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00001100
Evan Cheng06d64702006-08-11 08:59:35 +00001101 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00001102 emitCode("ReplaceUses(SDOperand(N.Val, " +
Evan Cheng30729b42007-09-17 22:26:41 +00001103 utostr(NumPatResults + (unsigned)InputHasChain)
1104 +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00001105 NeedReplace = true;
1106 }
1107
Evan Cheng30729b42007-09-17 22:26:41 +00001108 if (NeedReplace && InputHasChain)
1109 emitCode("ReplaceUses(SDOperand(N.Val, " +
1110 utostr(NumPatResults) + "), SDOperand(" + ChainName
1111 + ".Val, " + ChainName + ".ResNo" + "));");
Evan Cheng97938882005-12-22 02:24:50 +00001112
Evan Chenged66e852006-03-09 08:19:11 +00001113 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00001114 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00001115 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00001116 } else if (InputHasChain && !NodeHasChain) {
1117 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00001118 if (NodeHasOutFlag)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001119 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
Evan Cheng06d64702006-08-11 08:59:35 +00001120 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001121 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
Evan Cheng06d64702006-08-11 08:59:35 +00001122 "), " + ChainName + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00001123 }
Evan Cheng06d64702006-08-11 08:59:35 +00001124
Evan Cheng30729b42007-09-17 22:26:41 +00001125 emitCode("return ResNode;");
Evan Chengb915f312005-12-09 22:45:35 +00001126 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00001127 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00001128 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00001129 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00001130 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00001131 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001132 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00001133
1134 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1135 AllOps.push_back("InFlag");
1136
1137 unsigned NumOps = AllOps.size();
1138 if (NumOps) {
1139 if (!NodeHasOptInFlag && NumOps < 4) {
1140 for (unsigned i = 0; i != NumOps; ++i)
1141 Code += ", " + AllOps[i];
1142 } else {
1143 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1144 for (unsigned i = 0; i != NumOps; ++i) {
1145 OpsCode += AllOps[i];
1146 if (i != NumOps-1)
1147 OpsCode += ", ";
1148 }
1149 emitCode(OpsCode + " };");
1150 Code += ", Ops" + utostr(OpcNo) + ", ";
1151 Code += utostr(NumOps);
1152 }
1153 }
Evan Cheng95514ba2006-08-26 08:00:10 +00001154 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00001155 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1156 if (N->getTypeNum(0) != MVT::isVoid)
1157 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00001158 }
Evan Cheng4fba2812005-12-20 07:37:41 +00001159
Evan Cheng676d7312006-08-26 00:59:04 +00001160 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00001161 } else if (Op->isSubClassOf("SDNodeXForm")) {
1162 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00001163 // PatLeaf node - the operand may or may not be a leaf node. But it should
1164 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00001165 std::vector<std::string> Ops =
Evan Cheng30729b42007-09-17 22:26:41 +00001166 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Evan Cheng676d7312006-08-26 00:59:04 +00001167 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00001168 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00001169 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1170 + "(" + Ops.back() + ".Val);");
1171 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00001172 if (isRoot)
1173 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00001174 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00001175 } else {
1176 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001177 cerr << "\n";
Chris Lattner7893f132006-01-11 01:33:49 +00001178 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00001179 }
1180 }
1181
Chris Lattner488580c2006-01-28 19:06:51 +00001182 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1183 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00001184 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1185 /// for, this returns true otherwise false if Pat has all types.
1186 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00001187 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00001188 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00001189 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00001190 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00001191 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00001192 // The top level node type is checked outside of the select function.
1193 if (!isRoot)
1194 emitCheck(Prefix + ".Val->getValueType(0) == " +
1195 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00001196 return true;
Evan Chengb915f312005-12-09 22:45:35 +00001197 }
1198
Evan Cheng51fecc82006-01-09 18:27:06 +00001199 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +00001200 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +00001201 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1202 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1203 Prefix + utostr(OpNo)))
1204 return true;
1205 return false;
1206 }
1207
1208private:
Evan Cheng54597732006-01-26 00:22:25 +00001209 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00001210 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00001211 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00001212 bool &ChainEmitted, bool &InFlagDecled,
1213 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001214 const CodeGenTarget &T = CGP.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00001215 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +00001216 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1217 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Evan Chengb915f312005-12-09 22:45:35 +00001218 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1219 TreePatternNode *Child = N->getChild(i);
1220 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00001221 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1222 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00001223 } else {
1224 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00001225 if (!Child->getName().empty()) {
1226 std::string Name = RootName + utostr(OpNo);
1227 if (Duplicates.find(Name) != Duplicates.end())
1228 // A duplicate! Do not emit a copy for this node.
1229 continue;
1230 }
1231
Evan Chengb915f312005-12-09 22:45:35 +00001232 Record *RR = DI->getDef();
1233 if (RR->isSubClassOf("Register")) {
1234 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00001235 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00001236 if (!InFlagDecled) {
1237 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1238 InFlagDecled = true;
1239 } else
1240 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1241 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00001242 } else {
1243 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00001244 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001245 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00001246 ChainEmitted = true;
1247 }
Evan Cheng676d7312006-08-26 00:59:04 +00001248 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1249 if (!InFlagDecled) {
1250 emitCode("SDOperand InFlag(0, 0);");
1251 InFlagDecled = true;
1252 }
1253 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1254 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner6cefb772008-01-05 22:25:12 +00001255 ", " + getQualifiedName(RR) +
Evan Cheng7a33db02006-08-26 07:39:28 +00001256 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00001257 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00001258 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1259 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00001260 }
1261 }
1262 }
1263 }
1264 }
Evan Cheng54597732006-01-26 00:22:25 +00001265
Evan Cheng676d7312006-08-26 00:59:04 +00001266 if (HasInFlag) {
1267 if (!InFlagDecled) {
1268 emitCode("SDOperand InFlag = " + RootName +
1269 ".getOperand(" + utostr(OpNo) + ");");
1270 InFlagDecled = true;
1271 } else
1272 emitCode("InFlag = " + RootName +
1273 ".getOperand(" + utostr(OpNo) + ");");
1274 emitCode("AddToISelQueue(InFlag);");
1275 }
Evan Chengb915f312005-12-09 22:45:35 +00001276 }
1277};
1278
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001279/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1280/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001281/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001282void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001283 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001284 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001285 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00001286 std::vector<std::string> &TargetVTs) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001287 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001288 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001289 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00001290 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00001291
Chris Lattner8fc35682005-09-23 23:16:51 +00001292 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001293 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001294 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001295
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001296 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner200c57e2008-01-05 22:58:54 +00001297 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001298
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001299 // At this point, we know that we structurally match the pattern, but the
1300 // types of the nodes may not match. Figure out the fewest number of type
1301 // comparisons we need to emit. For example, if there is only one integer
1302 // type supported by a target, there should be no type comparisons at all for
1303 // integer patterns!
1304 //
1305 // To figure out the fewest number of type checks needed, clone the pattern,
1306 // remove the types, then perform type inference on the pattern as a whole.
1307 // If there are unresolved types, emit an explicit check for those types,
1308 // apply the type to the tree, then rerun type inference. Iterate until all
1309 // types are resolved.
1310 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001311 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001312 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001313
1314 do {
1315 // Resolve/propagate as many types as possible.
1316 try {
1317 bool MadeChange = true;
1318 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001319 MadeChange = Pat->ApplyTypeConstraints(TP,
1320 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001321 } catch (...) {
1322 assert(0 && "Error: could not find consistent types for something we"
1323 " already decided was ok!");
1324 abort();
1325 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001326
Chris Lattner7e82f132005-10-15 21:34:21 +00001327 // Insert a check for an unresolved type and add it to the tree. If we find
1328 // an unresolved type to add a check for, this returns true and we iterate,
1329 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001330 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001331
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001332 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001333 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001334 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001335}
1336
Chris Lattner24e00a42006-01-29 04:41:05 +00001337/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1338/// a line causes any of them to be empty, remove them and return true when
1339/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001340static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001341 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001342 &Patterns) {
1343 bool ErasedPatterns = false;
1344 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1345 Patterns[i].second.pop_back();
1346 if (Patterns[i].second.empty()) {
1347 Patterns.erase(Patterns.begin()+i);
1348 --i; --e;
1349 ErasedPatterns = true;
1350 }
1351 }
1352 return ErasedPatterns;
1353}
1354
Chris Lattner8bc74722006-01-29 04:25:26 +00001355/// EmitPatterns - Emit code for at least one pattern, but try to group common
1356/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001357void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001358 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001359 &Patterns, unsigned Indent,
1360 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001361 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001362 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001363 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001364
1365 if (Patterns.empty()) return;
1366
Chris Lattner24e00a42006-01-29 04:41:05 +00001367 // Figure out how many patterns share the next code line. Explicitly copy
1368 // FirstCodeLine so that we don't invalidate a reference when changing
1369 // Patterns.
1370 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001371 unsigned LastMatch = Patterns.size()-1;
1372 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1373 --LastMatch;
1374
1375 // If not all patterns share this line, split the list into two pieces. The
1376 // first chunk will use this line, the second chunk won't.
1377 if (LastMatch != 0) {
1378 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1379 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1380
1381 // FIXME: Emit braces?
1382 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001383 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001384 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1385 Pattern.getSrcPattern()->print(OS);
1386 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1387 Pattern.getDstPattern()->print(OS);
1388 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001389 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001390 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001391 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001392 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001393 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001394 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001395 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001396 }
Evan Cheng676d7312006-08-26 00:59:04 +00001397 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001398 OS << std::string(Indent, ' ') << "{\n";
1399 Indent += 2;
1400 }
1401 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001402 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001403 Indent -= 2;
1404 OS << std::string(Indent, ' ') << "}\n";
1405 }
1406
1407 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001408 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001409 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1410 Pattern.getSrcPattern()->print(OS);
1411 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1412 Pattern.getDstPattern()->print(OS);
1413 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001414 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001415 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001416 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001417 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001418 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001419 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001420 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001421 }
1422 EmitPatterns(Other, Indent, OS);
1423 return;
1424 }
1425
Chris Lattner24e00a42006-01-29 04:41:05 +00001426 // Remove this code from all of the patterns that share it.
1427 bool ErasedPatterns = EraseCodeLine(Patterns);
1428
Evan Cheng676d7312006-08-26 00:59:04 +00001429 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001430
1431 // Otherwise, every pattern in the list has this line. Emit it.
1432 if (!isPredicate) {
1433 // Normal code.
1434 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1435 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001436 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1437
1438 // If the next code line is another predicate, and if all of the pattern
1439 // in this group share the same next line, emit it inline now. Do this
1440 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001441 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00001442 // Check that all of fhe patterns in Patterns end with the same predicate.
1443 bool AllEndWithSamePredicate = true;
1444 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1445 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1446 AllEndWithSamePredicate = false;
1447 break;
1448 }
1449 // If all of the predicates aren't the same, we can't share them.
1450 if (!AllEndWithSamePredicate) break;
1451
1452 // Otherwise we can. Emit it shared now.
1453 OS << " &&\n" << std::string(Indent+4, ' ')
1454 << Patterns.back().second.back().second;
1455 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001456 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001457
1458 OS << ") {\n";
1459 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001460 }
1461
1462 EmitPatterns(Patterns, Indent, OS);
1463
1464 if (isPredicate)
1465 OS << std::string(Indent-2, ' ') << "}\n";
1466}
1467
Chris Lattnerfe718932008-01-06 01:10:31 +00001468static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001469 return CGP.getSDNodeInfo(Op).getEnumName();
Evan Cheng892aaf82006-11-08 23:01:03 +00001470}
Chris Lattner8bc74722006-01-29 04:25:26 +00001471
Evan Cheng892aaf82006-11-08 23:01:03 +00001472static std::string getLegalCName(std::string OpName) {
1473 std::string::size_type pos = OpName.find("::");
1474 if (pos != std::string::npos)
1475 OpName.replace(pos, 2, "_");
1476 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001477}
1478
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001479void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001480 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner6cefb772008-01-05 22:25:12 +00001481
Chris Lattnerf7560ed2006-11-20 18:54:33 +00001482 // Get the namespace to insert instructions into. Make sure not to pick up
1483 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1484 // instruction or something.
1485 std::string InstNS;
1486 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1487 e = Target.inst_end(); i != e; ++i) {
1488 InstNS = i->second.Namespace;
1489 if (InstNS != "TargetInstrInfo")
1490 break;
1491 }
1492
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001493 if (!InstNS.empty()) InstNS += "::";
1494
Chris Lattner602f6922006-01-04 00:25:00 +00001495 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001496 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001497 // All unique target node emission functions.
1498 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001499 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001500 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001501 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001502
1503 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001504 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001505 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001506 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001507 } else {
1508 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001509 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001510 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001511 push_back(&Pattern);
Chris Lattner200c57e2008-01-05 22:58:54 +00001512 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001513 std::vector<Record*> OpNodes = CP->getRootNodes();
1514 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001515 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1516 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001517 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001518 }
1519 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001520 cerr << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001521 Node->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001522 cerr << "' on tree pattern '";
Chris Lattner6cefb772008-01-05 22:25:12 +00001523 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001524 exit(1);
1525 }
1526 }
1527 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001528
1529 // For each opcode, there might be multiple select functions, one per
1530 // ValueType of the node (or its first operand if it doesn't produce a
1531 // non-chain result.
1532 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1533
Chris Lattner602f6922006-01-04 00:25:00 +00001534 // Emit one Select_* method for each top-level opcode. We do this instead of
1535 // emitting one giant switch statement to support compilers where this will
1536 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001537 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001538 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1539 PBOI != E; ++PBOI) {
1540 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001541 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001542 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1543
Chris Lattner602f6922006-01-04 00:25:00 +00001544 // We want to emit all of the matching code now. However, we want to emit
1545 // the matches in order of minimal cost. Sort the patterns so the least
1546 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00001547 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001548 PatternSortingPredicate(CGP));
Evan Cheng21ad3922006-02-07 00:37:41 +00001549
Chris Lattner706d2d32006-08-09 16:44:44 +00001550 // Split them into groups by type.
Chris Lattner60d81392008-01-05 22:30:17 +00001551 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001552 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001553 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001554 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner706d2d32006-08-09 16:44:44 +00001555 MVT::ValueType VT = SrcPat->getTypeNum(0);
Chris Lattner60d81392008-01-05 22:30:17 +00001556 std::map<MVT::ValueType,
1557 std::vector<const PatternToMatch*> >::iterator TI =
Chris Lattner706d2d32006-08-09 16:44:44 +00001558 PatternsByType.find(VT);
1559 if (TI != PatternsByType.end())
1560 TI->second.push_back(Pat);
1561 else {
Chris Lattner60d81392008-01-05 22:30:17 +00001562 std::vector<const PatternToMatch*> PVec;
Chris Lattner706d2d32006-08-09 16:44:44 +00001563 PVec.push_back(Pat);
1564 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001565 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001566 }
1567
Chris Lattner60d81392008-01-05 22:30:17 +00001568 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001569 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1570 ++II) {
1571 MVT::ValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001572 std::vector<const PatternToMatch*> &Patterns = II->second;
Chris Lattner64906972006-09-21 18:28:27 +00001573 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1574 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001575
Chris Lattner60d81392008-01-05 22:30:17 +00001576 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001577 std::vector<std::vector<std::string> > PatternOpcodes;
1578 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001579 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00001580 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1581 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001582 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001583 std::vector<std::string> TargetOpcodes;
1584 std::vector<std::string> TargetVTs;
1585 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1586 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00001587 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1588 PatternDecls.push_back(GeneratedDecl);
1589 PatternOpcodes.push_back(TargetOpcodes);
1590 PatternVTs.push_back(TargetVTs);
1591 }
1592
1593 // Scan the code to see if all of the patterns are reachable and if it is
1594 // possible that the last one might not match.
1595 bool mightNotMatch = true;
1596 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1597 CodeList &GeneratedCode = CodeForPatterns[i].second;
1598 mightNotMatch = false;
1599
1600 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001601 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00001602 mightNotMatch = true;
1603 break;
1604 }
1605 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001606
Chris Lattner706d2d32006-08-09 16:44:44 +00001607 // If this pattern definitely matches, and if it isn't the last one, the
1608 // patterns after it CANNOT ever match. Error out.
1609 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001610 cerr << "Pattern '";
1611 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1612 cerr << "' is impossible to select!\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001613 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001614 }
1615 }
1616
Chris Lattner706d2d32006-08-09 16:44:44 +00001617 // Factor target node emission code (emitted by EmitResultCode) into
1618 // separate functions. Uniquing and share them among all instruction
1619 // selection routines.
1620 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1621 CodeList &GeneratedCode = CodeForPatterns[i].second;
1622 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1623 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001624 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001625 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001626 int CodeSize = (int)GeneratedCode.size();
1627 int LastPred = -1;
1628 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001629 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001630 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001631 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1632 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001633 }
1634
Evan Cheng9ade2182006-08-26 05:34:46 +00001635 std::string CalleeCode = "(const SDOperand &N";
1636 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001637 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1638 CalleeCode += ", unsigned Opc" + utostr(j);
1639 CallerCode += ", " + TargetOpcodes[j];
1640 }
1641 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1642 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1643 CallerCode += ", " + TargetVTs[j];
1644 }
Evan Chengf5493192006-08-26 01:02:19 +00001645 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001646 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001647 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00001648 CalleeCode += ", SDOperand &" + Name;
1649 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001650 }
1651 CallerCode += ");";
1652 CalleeCode += ") ";
1653 // Prevent emission routines from being inlined to reduce selection
1654 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00001655 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00001656 CalleeCode += "{\n";
1657
1658 for (std::vector<std::string>::const_reverse_iterator
1659 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1660 CalleeCode += " " + *I + "\n";
1661
Evan Chengf5493192006-08-26 01:02:19 +00001662 for (int j = LastPred+1; j < CodeSize; ++j)
1663 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001664 for (int j = LastPred+1; j < CodeSize; ++j)
1665 GeneratedCode.pop_back();
1666 CalleeCode += "}\n";
1667
1668 // Uniquing the emission routines.
1669 unsigned EmitFuncNum;
1670 std::map<std::string, unsigned>::iterator EFI =
1671 EmitFunctions.find(CalleeCode);
1672 if (EFI != EmitFunctions.end()) {
1673 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001674 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001675 EmitFuncNum = EmitFunctions.size();
1676 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00001677 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001678 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001679
Chris Lattner706d2d32006-08-09 16:44:44 +00001680 // Replace the emission code within selection routines with calls to the
1681 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00001682 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00001683 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001684 }
1685
Chris Lattner706d2d32006-08-09 16:44:44 +00001686 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001687 std::string OpVTStr;
Chris Lattner33a40042006-11-14 22:17:10 +00001688 if (OpVT == MVT::iPTR) {
1689 OpVTStr = "_iPTR";
1690 } else if (OpVT == MVT::isVoid) {
1691 // Nodes with a void result actually have a first result type of either
1692 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1693 // void to this case, we handle it specially here.
1694 } else {
1695 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1696 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001697 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1698 OpcodeVTMap.find(OpName);
1699 if (OpVTI == OpcodeVTMap.end()) {
1700 std::vector<std::string> VTSet;
1701 VTSet.push_back(OpVTStr);
1702 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1703 } else
1704 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001705
Evan Cheng892aaf82006-11-08 23:01:03 +00001706 OS << "SDNode *Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00001707 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001708
Chris Lattner706d2d32006-08-09 16:44:44 +00001709 // Loop through and reverse all of the CodeList vectors, as we will be
1710 // accessing them from their logical front, but accessing the end of a
1711 // vector is more efficient.
1712 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1713 CodeList &GeneratedCode = CodeForPatterns[i].second;
1714 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001715 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001716
1717 // Next, reverse the list of patterns itself for the same reason.
1718 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1719
1720 // Emit all of the patterns now, grouped together to share code.
1721 EmitPatterns(CodeForPatterns, 2, OS);
1722
Chris Lattner64906972006-09-21 18:28:27 +00001723 // If the last pattern has predicates (which could fail) emit code to
1724 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001725 if (mightNotMatch) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001726 OS << " cerr << \"Cannot yet select: \";\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00001727 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1728 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1729 OpName != "ISD::INTRINSIC_VOID") {
Chris Lattner706d2d32006-08-09 16:44:44 +00001730 OS << " N.Val->dump(CurDAG);\n";
1731 } else {
1732 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1733 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001734 << " cerr << \"intrinsic %\"<< "
Chris Lattner706d2d32006-08-09 16:44:44 +00001735 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1736 }
Bill Wendlingf5da1332006-12-07 22:21:48 +00001737 OS << " cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001738 << " abort();\n"
1739 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001740 }
1741 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001742 }
Chris Lattner602f6922006-01-04 00:25:00 +00001743 }
1744
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001745 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00001746 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001747 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00001748 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1749
1750 << " // Ensure that the asm operands are themselves selected.\n"
1751 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1752 << " AddToISelQueue(Ops[j]);\n\n"
1753
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001754 << " std::vector<MVT::ValueType> VTs;\n"
1755 << " VTs.push_back(MVT::Other);\n"
1756 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00001757 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1758 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00001759 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001760 << "}\n\n";
1761
Jim Laskeya683f9b2007-01-26 17:29:20 +00001762 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1763 << " SDOperand Chain = N.getOperand(0);\n"
1764 << " SDOperand N1 = N.getOperand(1);\n"
Jim Laskey844b8922007-01-26 23:00:54 +00001765 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1766 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001767 << " AddToISelQueue(Chain);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001768 << " SDOperand Ops[] = { Tmp, Chain };\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001769 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001770 << " MVT::Other, Ops, 2);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001771 << "}\n\n";
1772
Christopher Lamb08d52072007-07-26 07:48:21 +00001773 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1774 << " SDOperand N0 = N.getOperand(0);\n"
1775 << " SDOperand N1 = N.getOperand(1);\n"
1776 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1777 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1778 << " AddToISelQueue(N0);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001779 << " SDOperand Ops[] = { N0, Tmp };\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001780 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001781 << " N.getValueType(), Ops, 2);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001782 << "}\n\n";
1783
1784 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1785 << " SDOperand N0 = N.getOperand(0);\n"
1786 << " SDOperand N1 = N.getOperand(1);\n"
1787 << " SDOperand N2 = N.getOperand(2);\n"
1788 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1789 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1790 << " AddToISelQueue(N1);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001791 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001792 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
Evan Cheng3393f892007-10-12 08:39:02 +00001793 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001794 << " N.getValueType(), Ops+1, 2);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001795 << " } else {\n"
1796 << " AddToISelQueue(N0);\n"
Evan Cheng3393f892007-10-12 08:39:02 +00001797 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001798 << " N.getValueType(), Ops, 3);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001799 << " }\n"
1800 << "}\n\n";
1801
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001802 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00001803 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001804 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001805 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00001806 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001807 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00001808 << " }\n\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00001809 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001810 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001811 << " default: break;\n"
1812 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001813 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001814 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001815 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001816 << " case ISD::TargetConstant:\n"
1817 << " case ISD::TargetConstantPool:\n"
1818 << " case ISD::TargetFrameIndex:\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00001819 << " case ISD::TargetExternalSymbol:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001820 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001821 << " case ISD::TargetGlobalTLSAddress:\n"
Evan Cheng34167212006-02-09 00:37:58 +00001822 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001823 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001824 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001825 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001826 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00001827 << " AddToISelQueue(N.getOperand(0));\n"
1828 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001829 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001830 << " }\n"
1831 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00001832 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001833 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00001834 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1835 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001836 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001837 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001838 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001839 << " case ISD::LABEL: return Select_LABEL(N);\n"
1840 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1841 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001842
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001843
Chris Lattner602f6922006-01-04 00:25:00 +00001844 // Loop over all of the case statements, emiting a call to each method we
1845 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001846 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001847 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1848 PBOI != E; ++PBOI) {
1849 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001850 // Potentially multiple versions of select for this opcode. One for each
1851 // ValueType of the node (or its first true operand if it doesn't produce a
1852 // result.
1853 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1854 OpcodeVTMap.find(OpName);
1855 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001856 OS << " case " << OpName << ": {\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00001857 // Keep track of whether we see a pattern that has an iPtr result.
1858 bool HasPtrPattern = false;
1859 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001860
Evan Cheng425e8c72007-09-04 20:18:28 +00001861 OS << " switch (NVT) {\n";
1862 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1863 std::string &VTStr = OpVTs[i];
1864 if (VTStr.empty()) {
1865 HasDefaultPattern = true;
1866 continue;
1867 }
Chris Lattner717a6112006-11-14 21:50:27 +00001868
Evan Cheng425e8c72007-09-04 20:18:28 +00001869 // If this is a match on iPTR: don't emit it directly, we need special
1870 // code.
1871 if (VTStr == "_iPTR") {
1872 HasPtrPattern = true;
1873 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00001874 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001875 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1876 << " return Select_" << getLegalCName(OpName)
1877 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001878 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001879 OS << " default:\n";
1880
1881 // If there is an iPTR result version of this pattern, emit it here.
1882 if (HasPtrPattern) {
1883 OS << " if (NVT == TLI.getPointerTy())\n";
1884 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1885 }
1886 if (HasDefaultPattern) {
1887 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1888 }
1889 OS << " break;\n";
1890 OS << " }\n";
1891 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001892 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00001893 }
Chris Lattner81303322005-09-23 19:36:15 +00001894
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001895 OS << " } // end of big switch.\n\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001896 << " cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00001897 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1898 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1899 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00001900 << " N.Val->dump(CurDAG);\n"
1901 << " } else {\n"
1902 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1903 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001904 << " cerr << \"intrinsic %\"<< "
1905 "Intrinsic::getName((Intrinsic::ID)iid);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00001906 << " }\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001907 << " cerr << '\\n';\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001908 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001909 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001910 << "}\n";
1911}
1912
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001913void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001914 EmitSourceFileHeader("DAG Instruction Selector for the " +
1915 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001916
Chris Lattner1f39e292005-09-14 00:09:24 +00001917 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1918 << "// *** instruction selector class. These functions are really "
1919 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001920
Chris Lattner8dc728e2006-08-27 13:16:24 +00001921 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00001922
Chris Lattner706d2d32006-08-09 16:44:44 +00001923 OS << "// Instruction selector priority queue:\n"
1924 << "std::vector<SDNode*> ISelQueue;\n";
1925 OS << "/// Keep track of nodes which have already been added to queue.\n"
1926 << "unsigned char *ISelQueued;\n";
1927 OS << "/// Keep track of nodes which have already been selected.\n"
1928 << "unsigned char *ISelSelected;\n";
1929 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1930 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00001931
Evan Cheng4326ef52006-10-12 02:08:53 +00001932 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1933 OS << "/// not reach Op.\n";
1934 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1935 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1936 OS << " return true;\n";
1937 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1938 OS << " return false;\n";
1939 OS << " else if (Chain->getNumOperands() > 0) {\n";
1940 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1941 OS << " if (C0.getValueType() == MVT::Other)\n";
1942 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1943 OS << " }\n";
1944 OS << " return true;\n";
1945 OS << "}\n";
1946
Chris Lattner706d2d32006-08-09 16:44:44 +00001947 OS << "/// Sorting functions for the selection queue.\n"
1948 << "struct isel_sort : public std::binary_function"
1949 << "<SDNode*, SDNode*, bool> {\n"
1950 << " bool operator()(const SDNode* left, const SDNode* right) "
1951 << "const {\n"
1952 << " return (left->getNodeId() > right->getNodeId());\n"
1953 << " }\n"
1954 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00001955
Chris Lattner706d2d32006-08-09 16:44:44 +00001956 OS << "inline void setQueued(int Id) {\n";
1957 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001958 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001959 OS << "inline bool isQueued(int Id) {\n";
1960 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001961 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001962 OS << "inline void setSelected(int Id) {\n";
1963 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001964 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001965 OS << "inline bool isSelected(int Id) {\n";
1966 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1967 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00001968
Chris Lattner8dc728e2006-08-27 13:16:24 +00001969 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001970 OS << " int Id = N.Val->getNodeId();\n";
1971 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1972 OS << " ISelQueue.push_back(N.Val);\n";
1973 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1974 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001975 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001976 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001977
Chris Lattner706d2d32006-08-09 16:44:44 +00001978 OS << "inline void RemoveKilled() {\n";
1979OS << " unsigned NumKilled = ISelKilled.size();\n";
1980 OS << " if (NumKilled) {\n";
1981 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
1982 OS << " SDNode *Temp = ISelKilled[i];\n";
Evan Cheng4f776162006-10-12 23:18:52 +00001983 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
1984 << "Temp), ISelQueue.end());\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001985 OS << " };\n";
1986 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
1987 OS << " ISelKilled.clear();\n";
1988 OS << " }\n";
1989 OS << "}\n\n";
1990
Chris Lattner8dc728e2006-08-27 13:16:24 +00001991 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner01d029b2007-10-15 06:10:22 +00001992 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001993 OS << " setSelected(F.Val->getNodeId());\n";
1994 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00001995 OS << "}\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001996 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
Evan Cheng30729b42007-09-17 22:26:41 +00001997 OS << " unsigned FNumVals = F->getNumValues();\n";
1998 OS << " unsigned TNumVals = T->getNumValues();\n";
1999 OS << " if (FNumVals != TNumVals) {\n";
2000 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2001 << "i < e; ++i)\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002002 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
Chris Lattner01d029b2007-10-15 06:10:22 +00002003 << "SDOperand(T, i), &ISelKilled);\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002004 OS << " } else {\n";
2005 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2006 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002007 OS << " setSelected(F->getNodeId());\n";
2008 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002009 OS << "}\n\n";
2010
Evan Chenge41bf822006-02-05 06:43:12 +00002011 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002012 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2013 OS << " SelectRootInit();\n";
2014 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2015 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2016 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2017 OS << " memset(ISelQueued, 0, NumBytes);\n";
2018 OS << " memset(ISelSelected, 0, NumBytes);\n";
2019 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00002020 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2021 << " // a reference to the root node, preventing it from being deleted,\n"
2022 << " // and tracking any changes of the root.\n"
2023 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2024 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002025 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002026 OS << " SDNode *Node = ISelQueue.front();\n";
2027 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2028 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002029 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00002030 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00002031 OS << " if (ResNode != Node) {\n";
2032 OS << " if (ResNode)\n";
2033 OS << " ReplaceUses(Node, ResNode);\n";
Evan Cheng1fae00f2006-10-12 20:35:19 +00002034 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2035 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2036 OS << " RemoveKilled();\n";
2037 OS << " }\n";
Evan Cheng966fd372006-09-11 02:24:43 +00002038 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002039 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002040 OS << " }\n";
2041 OS << "\n";
2042 OS << " delete[] ISelQueued;\n";
2043 OS << " ISelQueued = NULL;\n";
2044 OS << " delete[] ISelSelected;\n";
2045 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00002046 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00002047 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00002048
Chris Lattner443e3f92008-01-05 22:54:53 +00002049 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00002050 EmitPredicateFunctions(OS);
2051
Bill Wendlingf5da1332006-12-07 22:21:48 +00002052 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerfe718932008-01-06 01:10:31 +00002053 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00002054 I != E; ++I) {
2055 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2056 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Bill Wendlingf5da1332006-12-07 22:21:48 +00002057 DOUT << "\n";
2058 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00002059
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002060 // At this point, we have full information about the 'Patterns' we need to
2061 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002062 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002063 EmitInstructionSelector(OS);
2064
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002065}