blob: d685f701f0874afda88b661456890fe598135d3a [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
Dan Gohmanc6c391d2008-01-31 00:25:39 +0000314 /// LSI - Load/Store information.
315 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
316 /// for each memory access. This facilitates the use of AliasAnalysis in
317 /// the backend.
318 std::vector<std::string> LSI;
319
Evan Cheng676d7312006-08-26 00:59:04 +0000320 /// GeneratedCode - This is the buffer that we emit code to. The first int
Chris Lattner8a0604b2006-01-28 20:31:24 +0000321 /// indicates whether this is an exit predicate (something that should be
Evan Cheng676d7312006-08-26 00:59:04 +0000322 /// tested, and if true, the match fails) [when 1], or normal code to emit
323 /// [when 0], or initialization code to emit [when 2].
324 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Evan Cheng21ad3922006-02-07 00:37:41 +0000325 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
326 /// the set of patterns for each top-level opcode.
Evan Chengf5493192006-08-26 01:02:19 +0000327 std::set<std::string> &GeneratedDecl;
Evan Chengfceb57a2006-07-15 08:45:20 +0000328 /// TargetOpcodes - The target specific opcodes used by the resulting
329 /// instructions.
330 std::vector<std::string> &TargetOpcodes;
Evan Chengf8729402006-07-16 06:12:52 +0000331 std::vector<std::string> &TargetVTs;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000332
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000333 std::string ChainName;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000334 unsigned TmpNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000335 unsigned OpcNo;
Evan Chengf8729402006-07-16 06:12:52 +0000336 unsigned VTNo;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000337
338 void emitCheck(const std::string &S) {
339 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000340 GeneratedCode.push_back(std::make_pair(1, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000341 }
342 void emitCode(const std::string &S) {
343 if (!S.empty())
Evan Cheng676d7312006-08-26 00:59:04 +0000344 GeneratedCode.push_back(std::make_pair(0, S));
345 }
346 void emitInit(const std::string &S) {
347 if (!S.empty())
348 GeneratedCode.push_back(std::make_pair(2, S));
Chris Lattner8a0604b2006-01-28 20:31:24 +0000349 }
Evan Chengf5493192006-08-26 01:02:19 +0000350 void emitDecl(const std::string &S) {
Evan Cheng21ad3922006-02-07 00:37:41 +0000351 assert(!S.empty() && "Invalid declaration");
Evan Chengf5493192006-08-26 01:02:19 +0000352 GeneratedDecl.insert(S);
Evan Cheng21ad3922006-02-07 00:37:41 +0000353 }
Evan Chengfceb57a2006-07-15 08:45:20 +0000354 void emitOpcode(const std::string &Opc) {
355 TargetOpcodes.push_back(Opc);
356 OpcNo++;
357 }
Evan Chengf8729402006-07-16 06:12:52 +0000358 void emitVT(const std::string &VT) {
359 TargetVTs.push_back(VT);
360 VTNo++;
361 }
Evan Chengb915f312005-12-09 22:45:35 +0000362public:
Chris Lattnerfe718932008-01-06 01:10:31 +0000363 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
Evan Cheng58e84a62005-12-14 22:02:59 +0000364 TreePatternNode *pattern, TreePatternNode *instr,
Evan Cheng676d7312006-08-26 00:59:04 +0000365 std::vector<std::pair<unsigned, std::string> > &gc,
Evan Chengf5493192006-08-26 01:02:19 +0000366 std::set<std::string> &gd,
Evan Chengfceb57a2006-07-15 08:45:20 +0000367 std::vector<std::string> &to,
Chris Lattner706d2d32006-08-09 16:44:44 +0000368 std::vector<std::string> &tv)
Chris Lattner6cefb772008-01-05 22:25:12 +0000369 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
Evan Cheng676d7312006-08-26 00:59:04 +0000370 GeneratedCode(gc), GeneratedDecl(gd),
371 TargetOpcodes(to), TargetVTs(tv),
Chris Lattner706d2d32006-08-09 16:44:44 +0000372 TmpNo(0), OpcNo(0), VTNo(0) {}
Evan Chengb915f312005-12-09 22:45:35 +0000373
374 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
375 /// if the match fails. At this point, we already know that the opcode for N
376 /// matches, and the SDNode for the result has the RootName specified name.
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000377 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
378 const std::string &RootName, const std::string &ChainSuffix,
379 bool &FoundChain) {
Dan Gohmanc6c391d2008-01-31 00:25:39 +0000380
381 // Save loads/stores matched by a pattern.
382 if (!N->isLeaf() && N->getName().empty() &&
383 ((N->getOperator()->getName() == "ld") ||
384 (N->getOperator()->getName() == "st") ||
385 (N->getOperator()->getName() == "ist"))) {
386 LSI.push_back(RootName);
387 }
388
Evan Chenge41bf822006-02-05 06:43:12 +0000389 bool isRoot = (P == NULL);
Evan Cheng58e84a62005-12-14 22:02:59 +0000390 // Emit instruction predicates. Each predicate is just a string for now.
391 if (isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000392 std::string PredicateCheck;
Evan Cheng58e84a62005-12-14 22:02:59 +0000393 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
394 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
395 Record *Def = Pred->getDef();
Chris Lattner8a0604b2006-01-28 20:31:24 +0000396 if (!Def->isSubClassOf("Predicate")) {
Jim Laskey16d42c62006-07-11 18:25:13 +0000397#ifndef NDEBUG
398 Def->dump();
399#endif
Evan Cheng58e84a62005-12-14 22:02:59 +0000400 assert(0 && "Unknown predicate type!");
401 }
Chris Lattner8a0604b2006-01-28 20:31:24 +0000402 if (!PredicateCheck.empty())
Chris Lattnerbc7fa522006-09-19 00:41:36 +0000403 PredicateCheck += " && ";
Chris Lattner67a202b2006-01-28 20:43:52 +0000404 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
Evan Cheng58e84a62005-12-14 22:02:59 +0000405 }
406 }
Chris Lattner8a0604b2006-01-28 20:31:24 +0000407
408 emitCheck(PredicateCheck);
Evan Cheng58e84a62005-12-14 22:02:59 +0000409 }
410
Evan Chengb915f312005-12-09 22:45:35 +0000411 if (N->isLeaf()) {
412 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000413 emitCheck("cast<ConstantSDNode>(" + RootName +
Chris Lattner67a202b2006-01-28 20:43:52 +0000414 ")->getSignExtended() == " + itostr(II->getValue()));
Evan Chengb915f312005-12-09 22:45:35 +0000415 return;
416 } else if (!NodeIsComplexPattern(N)) {
417 assert(0 && "Cannot match this as a leaf value!");
418 abort();
419 }
420 }
421
Chris Lattner488580c2006-01-28 19:06:51 +0000422 // If this node has a name associated with it, capture it in VariableMap. If
Evan Chengb915f312005-12-09 22:45:35 +0000423 // we already saw this in the pattern, emit code to verify dagness.
424 if (!N->getName().empty()) {
425 std::string &VarMapEntry = VariableMap[N->getName()];
426 if (VarMapEntry.empty()) {
427 VarMapEntry = RootName;
428 } else {
429 // If we get here, this is a second reference to a specific name. Since
430 // we already have checked that the first reference is valid, we don't
431 // have to recursively match it, just check that it's the same as the
432 // previously named thing.
Chris Lattner67a202b2006-01-28 20:43:52 +0000433 emitCheck(VarMapEntry + " == " + RootName);
Evan Chengb915f312005-12-09 22:45:35 +0000434 return;
435 }
Evan Chengf805c2e2006-01-12 19:35:54 +0000436
437 if (!N->isLeaf())
438 OperatorMap[N->getName()] = N->getOperator();
Evan Chengb915f312005-12-09 22:45:35 +0000439 }
440
441
442 // Emit code to load the child nodes and match their contents recursively.
443 unsigned OpNo = 0;
Chris Lattner6cefb772008-01-05 22:25:12 +0000444 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
445 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Evan Cheng1feeeec2006-01-26 19:13:45 +0000446 bool EmittedUseCheck = false;
Evan Cheng86217892005-12-12 19:37:43 +0000447 if (HasChain) {
Evan Cheng76356d92006-01-20 01:11:03 +0000448 if (NodeHasChain)
449 OpNo = 1;
Evan Chengb915f312005-12-09 22:45:35 +0000450 if (!isRoot) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000451 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +0000452 emitCheck(RootName + ".hasOneUse()");
Evan Cheng1feeeec2006-01-26 19:13:45 +0000453 EmittedUseCheck = true;
Evan Chenge41bf822006-02-05 06:43:12 +0000454 if (NodeHasChain) {
Evan Chenge41bf822006-02-05 06:43:12 +0000455 // If the immediate use can somehow reach this node through another
456 // path, then can't fold it either or it will create a cycle.
457 // e.g. In the following diagram, XX can reach ld through YY. If
458 // ld is folded into XX, then YY is both a predecessor and a successor
459 // of XX.
460 //
461 // [ld]
462 // ^ ^
463 // | |
464 // / \---
465 // / [YY]
466 // | ^
467 // [XX]-------|
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000468 bool NeedCheck = false;
469 if (P != Pattern)
470 NeedCheck = true;
471 else {
Chris Lattner6cefb772008-01-05 22:25:12 +0000472 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000473 NeedCheck =
Chris Lattner6cefb772008-01-05 22:25:12 +0000474 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
475 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
476 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Evan Chengce1381a2006-10-14 08:30:15 +0000477 PInfo.getNumOperands() > 1 ||
Evan Cheng94b30402006-10-11 21:02:01 +0000478 PInfo.hasProperty(SDNPHasChain) ||
479 PInfo.hasProperty(SDNPInFlag) ||
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000480 PInfo.hasProperty(SDNPOptInFlag);
481 }
482
483 if (NeedCheck) {
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000484 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner706d2d32006-08-09 16:44:44 +0000485 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
Evan Chengce1381a2006-10-14 08:30:15 +0000486 ".Val, N.Val)");
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000487 }
Evan Chenge41bf822006-02-05 06:43:12 +0000488 }
Evan Chengb915f312005-12-09 22:45:35 +0000489 }
Evan Chenge41bf822006-02-05 06:43:12 +0000490
Evan Chengc15d18c2006-01-27 22:13:45 +0000491 if (NodeHasChain) {
Evan Cheng4326ef52006-10-12 02:08:53 +0000492 if (FoundChain) {
493 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
494 "IsChainCompatible(" + ChainName + ".Val, " +
495 RootName + ".Val))");
496 OrigChains.push_back(std::make_pair(ChainName, RootName));
497 } else
Evan Chenge6389932006-07-21 22:19:51 +0000498 FoundChain = true;
Evan Chenge4a8a6e2006-02-03 06:22:41 +0000499 ChainName = "Chain" + ChainSuffix;
Evan Cheng676d7312006-08-26 00:59:04 +0000500 emitInit("SDOperand " + ChainName + " = " + RootName +
Evan Chenge6389932006-07-21 22:19:51 +0000501 ".getOperand(0);");
Evan Cheng1cf6db22006-01-06 00:41:12 +0000502 }
Evan Chengb915f312005-12-09 22:45:35 +0000503 }
504
Evan Cheng54597732006-01-26 00:22:25 +0000505 // Don't fold any node which reads or writes a flag and has multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +0000506 // FIXME: We really need to separate the concepts of flag and "glue". Those
Evan Cheng54597732006-01-26 00:22:25 +0000507 // real flag results, e.g. X86CMP output, can have multiple uses.
Evan Chenge41bf822006-02-05 06:43:12 +0000508 // FIXME: If the optional incoming flag does not exist. Then it is ok to
509 // fold it.
Evan Cheng1feeeec2006-01-26 19:13:45 +0000510 if (!isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000511 (PatternHasProperty(N, SDNPInFlag, CGP) ||
512 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
513 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Evan Cheng1feeeec2006-01-26 19:13:45 +0000514 if (!EmittedUseCheck) {
Chris Lattner8a0604b2006-01-28 20:31:24 +0000515 // Multiple uses of actual result?
Chris Lattner67a202b2006-01-28 20:43:52 +0000516 emitCheck(RootName + ".hasOneUse()");
Evan Cheng54597732006-01-26 00:22:25 +0000517 }
518 }
519
Evan Chengd3eea902006-10-09 21:02:17 +0000520 // If there is a node predicate for this, emit the call.
521 if (!N->getPredicateFn().empty())
522 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
523
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000524
Chris Lattner39e73f72006-10-11 04:05:55 +0000525 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
526 // a constant without a predicate fn that has more that one bit set, handle
527 // this as a special case. This is usually for targets that have special
528 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
529 // handling stuff). Using these instructions is often far more efficient
530 // than materializing the constant. Unfortunately, both the instcombiner
531 // and the dag combiner can often infer that bits are dead, and thus drop
532 // them from the mask in the dag. For example, it might turn 'AND X, 255'
533 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
534 // to handle this.
535 if (!N->isLeaf() &&
536 (N->getOperator()->getName() == "and" ||
537 N->getOperator()->getName() == "or") &&
538 N->getChild(1)->isLeaf() &&
539 N->getChild(1)->getPredicateFn().empty()) {
540 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
541 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
542 emitInit("SDOperand " + RootName + "0" + " = " +
543 RootName + ".getOperand(" + utostr(0) + ");");
544 emitInit("SDOperand " + RootName + "1" + " = " +
545 RootName + ".getOperand(" + utostr(1) + ");");
546
547 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
548 const char *MaskPredicate = N->getOperator()->getName() == "or"
549 ? "CheckOrMask(" : "CheckAndMask(";
550 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
551 RootName + "1), " + itostr(II->getValue()) + ")");
552
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000553 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
Chris Lattner39e73f72006-10-11 04:05:55 +0000554 ChainSuffix + utostr(0), FoundChain);
555 return;
556 }
557 }
558 }
559
Evan Chengb915f312005-12-09 22:45:35 +0000560 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Evan Cheng676d7312006-08-26 00:59:04 +0000561 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000562 RootName + ".getOperand(" +utostr(OpNo) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000563
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000564 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000565 ChainSuffix + utostr(OpNo), FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +0000566 }
567
Evan Cheng676d7312006-08-26 00:59:04 +0000568 // Handle cases when root is a complex pattern.
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000569 const ComplexPattern *CP;
Chris Lattner6cefb772008-01-05 22:25:12 +0000570 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Evan Cheng676d7312006-08-26 00:59:04 +0000571 std::string Fn = CP->getSelectFunc();
572 unsigned NumOps = CP->getNumOperands();
573 for (unsigned i = 0; i < NumOps; ++i) {
574 emitDecl("CPTmp" + utostr(i));
575 emitCode("SDOperand CPTmp" + utostr(i) + ";");
576 }
Evan Cheng94b30402006-10-11 21:02:01 +0000577 if (CP->hasProperty(SDNPHasChain)) {
578 emitDecl("CPInChain");
579 emitDecl("Chain" + ChainSuffix);
580 emitCode("SDOperand CPInChain;");
581 emitCode("SDOperand Chain" + ChainSuffix + ";");
582 }
Evan Cheng676d7312006-08-26 00:59:04 +0000583
Evan Cheng811731e2006-11-08 20:31:10 +0000584 std::string Code = Fn + "(" + RootName + ", " + RootName;
Evan Cheng676d7312006-08-26 00:59:04 +0000585 for (unsigned i = 0; i < NumOps; i++)
586 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +0000587 if (CP->hasProperty(SDNPHasChain)) {
588 ChainName = "Chain" + ChainSuffix;
589 Code += ", CPInChain, Chain" + ChainSuffix;
590 }
Evan Cheng676d7312006-08-26 00:59:04 +0000591 emitCheck(Code + ")");
592 }
Evan Chengb915f312005-12-09 22:45:35 +0000593 }
Chris Lattner39e73f72006-10-11 04:05:55 +0000594
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000595 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
596 const std::string &RootName,
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000597 const std::string &ChainSuffix, bool &FoundChain) {
598 if (!Child->isLeaf()) {
599 // If it's not a leaf, recursively match.
Chris Lattner6cefb772008-01-05 22:25:12 +0000600 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000601 emitCheck(RootName + ".getOpcode() == " +
602 CInfo.getEnumName());
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000603 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Chris Lattner6cefb772008-01-05 22:25:12 +0000604 if (NodeHasProperty(Child, SDNPHasChain, CGP))
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000605 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
606 } else {
607 // If this child has a name associated with it, capture it in VarMap. If
608 // we already saw this in the pattern, emit code to verify dagness.
609 if (!Child->getName().empty()) {
610 std::string &VarMapEntry = VariableMap[Child->getName()];
611 if (VarMapEntry.empty()) {
612 VarMapEntry = RootName;
613 } else {
614 // If we get here, this is a second reference to a specific name.
615 // Since we already have checked that the first reference is valid,
616 // we don't have to recursively match it, just check that it's the
617 // same as the previously named thing.
618 emitCheck(VarMapEntry + " == " + RootName);
619 Duplicates.insert(RootName);
620 return;
621 }
622 }
623
624 // Handle leaves of various types.
625 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
626 Record *LeafRec = DI->getDef();
Chris Lattner646085d2006-11-14 21:18:40 +0000627 if (LeafRec->isSubClassOf("RegisterClass") ||
628 LeafRec->getName() == "ptr_rc") {
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000629 // Handle register references. Nothing to do here.
630 } else if (LeafRec->isSubClassOf("Register")) {
631 // Handle register references.
632 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
633 // Handle complex pattern.
Chris Lattner6cefb772008-01-05 22:25:12 +0000634 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000635 std::string Fn = CP->getSelectFunc();
636 unsigned NumOps = CP->getNumOperands();
637 for (unsigned i = 0; i < NumOps; ++i) {
638 emitDecl("CPTmp" + utostr(i));
639 emitCode("SDOperand CPTmp" + utostr(i) + ";");
640 }
Evan Cheng94b30402006-10-11 21:02:01 +0000641 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000642 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Evan Cheng94b30402006-10-11 21:02:01 +0000643 FoldedChains.push_back(std::make_pair("CPInChain",
644 PInfo.getNumResults()));
645 ChainName = "Chain" + ChainSuffix;
646 emitDecl("CPInChain");
647 emitDecl(ChainName);
648 emitCode("SDOperand CPInChain;");
649 emitCode("SDOperand " + ChainName + ";");
650 }
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000651
Evan Cheng811731e2006-11-08 20:31:10 +0000652 std::string Code = Fn + "(N, ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000653 if (CP->hasProperty(SDNPHasChain)) {
654 std::string ParentName(RootName.begin(), RootName.end()-1);
Evan Cheng811731e2006-11-08 20:31:10 +0000655 Code += ParentName + ", ";
Evan Cheng13e9e9c2006-10-16 06:33:44 +0000656 }
657 Code += RootName;
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000658 for (unsigned i = 0; i < NumOps; i++)
659 Code += ", CPTmp" + utostr(i);
Evan Cheng94b30402006-10-11 21:02:01 +0000660 if (CP->hasProperty(SDNPHasChain))
661 Code += ", CPInChain, Chain" + ChainSuffix;
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000662 emitCheck(Code + ")");
663 } else if (LeafRec->getName() == "srcvalue") {
664 // Place holder for SRCVALUE nodes. Nothing to do here.
665 } else if (LeafRec->isSubClassOf("ValueType")) {
666 // Make sure this is the specified value type.
667 emitCheck("cast<VTSDNode>(" + RootName +
668 ")->getVT() == MVT::" + LeafRec->getName());
669 } else if (LeafRec->isSubClassOf("CondCode")) {
670 // Make sure this is the specified cond code.
671 emitCheck("cast<CondCodeSDNode>(" + RootName +
672 ")->get() == ISD::" + LeafRec->getName());
673 } else {
674#ifndef NDEBUG
675 Child->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +0000676 cerr << " ";
Chris Lattnerbe8e7212006-10-11 03:35:34 +0000677#endif
678 assert(0 && "Unknown leaf type!");
679 }
680
681 // If there is a node predicate for this, emit the call.
682 if (!Child->getPredicateFn().empty())
683 emitCheck(Child->getPredicateFn() + "(" + RootName +
684 ".Val)");
685 } else if (IntInit *II =
686 dynamic_cast<IntInit*>(Child->getLeafValue())) {
687 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
688 unsigned CTmp = TmpNo++;
689 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
690 RootName + ")->getSignExtended();");
691
692 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
693 } else {
694#ifndef NDEBUG
695 Child->dump();
696#endif
697 assert(0 && "Unknown leaf type!");
698 }
699 }
700 }
Evan Chengb915f312005-12-09 22:45:35 +0000701
702 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
703 /// we actually have to build a DAG!
Evan Cheng676d7312006-08-26 00:59:04 +0000704 std::vector<std::string>
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000705 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Evan Cheng676d7312006-08-26 00:59:04 +0000706 bool InFlagDecled, bool ResNodeDecled,
707 bool LikeLeaf = false, bool isRoot = false) {
708 // List of arguments of getTargetNode() or SelectNodeTo().
709 std::vector<std::string> NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000710 // This is something selected from the pattern we matched.
711 if (!N->getName().empty()) {
Scott Michel6be48d42008-01-29 02:29:31 +0000712 const std::string &VarName = N->getName();
713 std::string Val = VariableMap[VarName];
714 bool ModifiedVal = false;
Evan Chengb915f312005-12-09 22:45:35 +0000715 assert(!Val.empty() &&
716 "Variable referenced but not defined and not caught earlier!");
717 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
718 // Already selected this operand, just return the tmpval.
Evan Cheng676d7312006-08-26 00:59:04 +0000719 NodeOps.push_back(Val);
720 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000721 }
722
723 const ComplexPattern *CP;
724 unsigned ResNo = TmpNo++;
Evan Chengb915f312005-12-09 22:45:35 +0000725 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
Nate Begemanb73628b2005-12-30 00:12:56 +0000726 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Chris Lattner78593132006-01-29 20:01:35 +0000727 std::string CastType;
Scott Michel6be48d42008-01-29 02:29:31 +0000728 std::string TmpVar = "Tmp" + utostr(ResNo);
Nate Begemanb73628b2005-12-30 00:12:56 +0000729 switch (N->getTypeNum(0)) {
Chris Lattnerd8a17282007-01-17 07:45:12 +0000730 default:
731 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
732 << " type as an immediate constant. Aborting\n";
733 abort();
Chris Lattner78593132006-01-29 20:01:35 +0000734 case MVT::i1: CastType = "bool"; break;
735 case MVT::i8: CastType = "unsigned char"; break;
736 case MVT::i16: CastType = "unsigned short"; break;
737 case MVT::i32: CastType = "unsigned"; break;
738 case MVT::i64: CastType = "uint64_t"; break;
Evan Chengb915f312005-12-09 22:45:35 +0000739 }
Scott Michel6be48d42008-01-29 02:29:31 +0000740 emitCode("SDOperand " + TmpVar +
Evan Chengfceb57a2006-07-15 08:45:20 +0000741 " = CurDAG->getTargetConstant(((" + CastType +
742 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
743 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000744 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
745 // value if used multiple times by this pattern result.
Scott Michel6be48d42008-01-29 02:29:31 +0000746 Val = TmpVar;
747 ModifiedVal = true;
748 NodeOps.push_back(Val);
Evan Chengbb48e332006-01-12 07:54:57 +0000749 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
Evan Chengf805c2e2006-01-12 19:35:54 +0000750 Record *Op = OperatorMap[N->getName()];
751 // Transform ExternalSymbol to TargetExternalSymbol
752 if (Op && Op->getName() == "externalsym") {
Scott Michel6be48d42008-01-29 02:29:31 +0000753 std::string TmpVar = "Tmp"+utostr(ResNo);
754 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +0000755 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Evan Cheng2618d072006-05-17 20:37:59 +0000756 Val + ")->getSymbol(), " +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000757 getEnumName(N->getTypeNum(0)) + ");");
Chris Lattner64906972006-09-21 18:28:27 +0000758 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
759 // this value if used multiple times by this pattern result.
Scott Michel6be48d42008-01-29 02:29:31 +0000760 Val = TmpVar;
761 ModifiedVal = true;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000762 }
Scott Michel6be48d42008-01-29 02:29:31 +0000763 NodeOps.push_back(Val);
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +0000764 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
765 || N->getOperator()->getName() == "tglobaltlsaddr")) {
Evan Chengf805c2e2006-01-12 19:35:54 +0000766 Record *Op = OperatorMap[N->getName()];
767 // Transform GlobalAddress to TargetGlobalAddress
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +0000768 if (Op && (Op->getName() == "globaladdr" ||
769 Op->getName() == "globaltlsaddr")) {
Scott Michel6be48d42008-01-29 02:29:31 +0000770 std::string TmpVar = "Tmp" + utostr(ResNo);
771 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Chris Lattner8a0604b2006-01-28 20:31:24 +0000772 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
Evan Cheng2618d072006-05-17 20:37:59 +0000773 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000774 ");");
Chris Lattner64906972006-09-21 18:28:27 +0000775 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
776 // this value if used multiple times by this pattern result.
Scott Michel6be48d42008-01-29 02:29:31 +0000777 Val = TmpVar;
778 ModifiedVal = true;
Chris Lattner8a0604b2006-01-28 20:31:24 +0000779 }
Evan Cheng676d7312006-08-26 00:59:04 +0000780 NodeOps.push_back(Val);
Scott Michel6be48d42008-01-29 02:29:31 +0000781 } else if (!N->isLeaf()
782 && (N->getOperator()->getName() == "texternalsym"
783 || N->getOperator()->getName() == "tconstpool")) {
784 // Do not rewrite the variable name, since we don't generate a new
785 // temporary.
Evan Cheng676d7312006-08-26 00:59:04 +0000786 NodeOps.push_back(Val);
Chris Lattner6cefb772008-01-05 22:25:12 +0000787 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Evan Cheng676d7312006-08-26 00:59:04 +0000788 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
789 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
790 NodeOps.push_back("CPTmp" + utostr(i));
Evan Chengb0793f92006-05-25 00:21:44 +0000791 }
Evan Chengb915f312005-12-09 22:45:35 +0000792 } else {
Evan Cheng676d7312006-08-26 00:59:04 +0000793 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
Evan Cheng863bf5a2006-03-20 22:53:06 +0000794 // node even if it isn't one. Don't select it.
Evan Cheng676d7312006-08-26 00:59:04 +0000795 if (!LikeLeaf) {
796 emitCode("AddToISelQueue(" + Val + ");");
Chris Lattner706d2d32006-08-09 16:44:44 +0000797 if (isRoot && N->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +0000798 emitCode("ReplaceUses(N, " + Val + ");");
Evan Cheng06d64702006-08-11 08:59:35 +0000799 emitCode("return NULL;");
Chris Lattner706d2d32006-08-09 16:44:44 +0000800 }
Evan Cheng83e1a6a2006-03-23 02:35:32 +0000801 }
Evan Cheng676d7312006-08-26 00:59:04 +0000802 NodeOps.push_back(Val);
Evan Chengb915f312005-12-09 22:45:35 +0000803 }
Scott Michel6be48d42008-01-29 02:29:31 +0000804
805 if (ModifiedVal) {
806 VariableMap[VarName] = Val;
807 }
Evan Cheng676d7312006-08-26 00:59:04 +0000808 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000809 }
Evan Chengb915f312005-12-09 22:45:35 +0000810 if (N->isLeaf()) {
811 // If this is an explicit register reference, handle it.
812 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
813 unsigned ResNo = TmpNo++;
814 if (DI->getDef()->isSubClassOf("Register")) {
Evan Cheng676d7312006-08-26 00:59:04 +0000815 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner6cefb772008-01-05 22:25:12 +0000816 getQualifiedName(DI->getDef()) + ", " +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000817 getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000818 NodeOps.push_back("Tmp" + utostr(ResNo));
819 return NodeOps;
Evan Cheng7774be42007-07-05 07:19:45 +0000820 } else if (DI->getDef()->getName() == "zero_reg") {
821 emitCode("SDOperand Tmp" + utostr(ResNo) +
822 " = CurDAG->getRegister(0, " +
823 getEnumName(N->getTypeNum(0)) + ");");
824 NodeOps.push_back("Tmp" + utostr(ResNo));
825 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000826 }
827 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
828 unsigned ResNo = TmpNo++;
Nate Begemanb73628b2005-12-30 00:12:56 +0000829 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Evan Cheng676d7312006-08-26 00:59:04 +0000830 emitCode("SDOperand Tmp" + utostr(ResNo) +
Chris Lattner8a0604b2006-01-28 20:31:24 +0000831 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
Evan Cheng2618d072006-05-17 20:37:59 +0000832 ", " + getEnumName(N->getTypeNum(0)) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +0000833 NodeOps.push_back("Tmp" + utostr(ResNo));
834 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000835 }
836
Jim Laskey16d42c62006-07-11 18:25:13 +0000837#ifndef NDEBUG
838 N->dump();
839#endif
Evan Chengb915f312005-12-09 22:45:35 +0000840 assert(0 && "Unknown leaf type!");
Evan Cheng676d7312006-08-26 00:59:04 +0000841 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +0000842 }
843
844 Record *Op = N->getOperator();
845 if (Op->isSubClassOf("Instruction")) {
Chris Lattner6cefb772008-01-05 22:25:12 +0000846 const CodeGenTarget &CGT = CGP.getTargetInfo();
Evan Cheng7b05bd52005-12-23 22:11:47 +0000847 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner6cefb772008-01-05 22:25:12 +0000848 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattnerf1ab4f12008-01-06 01:52:22 +0000849 const TreePattern *InstPat = Inst.getPattern();
Evan Chengd23aa5a2007-09-25 01:48:59 +0000850 // FIXME: Assume actual pattern comes before "implicit".
Evan Cheng045953c2006-05-10 00:05:46 +0000851 TreePatternNode *InstPatNode =
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000852 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
853 : (InstPat ? InstPat->getTree(0) : NULL);
Evan Cheng045953c2006-05-10 00:05:46 +0000854 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengaeb7d4d2007-09-11 19:52:18 +0000855 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Evan Cheng045953c2006-05-10 00:05:46 +0000856 }
Chris Lattner8f707e12008-01-07 05:19:29 +0000857 bool HasVarOps = isRoot && II.isVariadic;
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000858 // FIXME: fix how we deal with physical register operands.
Evan Cheng045953c2006-05-10 00:05:46 +0000859 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000860 bool HasImpResults = isRoot && DstRegs.size() > 0;
Evan Cheng045953c2006-05-10 00:05:46 +0000861 bool NodeHasOptInFlag = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000862 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Evan Cheng045953c2006-05-10 00:05:46 +0000863 bool NodeHasInFlag = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000864 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengef61ed32007-09-07 23:59:02 +0000865 bool NodeHasOutFlag = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000866 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Evan Cheng045953c2006-05-10 00:05:46 +0000867 bool NodeHasChain = InstPatNode &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000868 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Evan Cheng3eff89b2006-05-10 02:47:57 +0000869 bool InputHasChain = isRoot &&
Chris Lattner6cefb772008-01-05 22:25:12 +0000870 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000871 unsigned NumResults = Inst.getNumResults();
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000872 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Evan Cheng4fba2812005-12-20 07:37:41 +0000873
Evan Chengfceb57a2006-07-15 08:45:20 +0000874 if (NodeHasOptInFlag) {
Evan Cheng676d7312006-08-26 00:59:04 +0000875 emitCode("bool HasInFlag = "
Evan Chengf8729402006-07-16 06:12:52 +0000876 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
Evan Chengfceb57a2006-07-15 08:45:20 +0000877 }
Evan Chenge945f4d2006-06-14 22:22:20 +0000878 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +0000879 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
Evan Cheng4fba2812005-12-20 07:37:41 +0000880
Evan Cheng823b7522006-01-19 21:57:10 +0000881 // How many results is this pattern expected to produce?
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000882 unsigned NumPatResults = 0;
Evan Cheng823b7522006-01-19 21:57:10 +0000883 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
884 MVT::ValueType VT = Pattern->getTypeNum(i);
885 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000886 NumPatResults++;
Evan Cheng823b7522006-01-19 21:57:10 +0000887 }
888
Evan Cheng4326ef52006-10-12 02:08:53 +0000889 if (OrigChains.size() > 0) {
890 // The original input chain is being ignored. If it is not just
891 // pointing to the op that's being folded, we should create a
892 // TokenFactor with it and the chain of the folded op as the new chain.
893 // We could potentially be doing multiple levels of folding, in that
894 // case, the TokenFactor can have more operands.
895 emitCode("SmallVector<SDOperand, 8> InChains;");
896 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
897 emitCode("if (" + OrigChains[i].first + ".Val != " +
898 OrigChains[i].second + ".Val) {");
899 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
900 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
901 emitCode("}");
902 }
903 emitCode("AddToISelQueue(" + ChainName + ");");
904 emitCode("InChains.push_back(" + ChainName + ");");
905 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
906 "&InChains[0], InChains.size());");
907 }
908
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000909 // Loop over all of the operands of the instruction pattern, emitting code
910 // to fill them all in. The node 'N' usually has number children equal to
911 // the number of input operands of the instruction. However, in cases
912 // where there are predicate operands for an instruction, we need to fill
913 // in the 'execute always' values. Match up the node operands to the
914 // instruction operands to do this.
Evan Cheng676d7312006-08-26 00:59:04 +0000915 std::vector<std::string> AllOps;
Evan Cheng39376d02007-05-15 01:19:51 +0000916 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000917 for (unsigned ChildNo = 0, InstOpNo = NumResults;
918 InstOpNo != II.OperandList.size(); ++InstOpNo) {
919 std::vector<std::string> Ops;
920
Evan Cheng59039632007-05-08 21:04:07 +0000921 // If this is a normal operand or a predicate operand without
922 // 'execute always', emit it.
923 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Evan Chenga9559392007-07-06 01:05:26 +0000924 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
925 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
Chris Lattner6cefb772008-01-05 22:25:12 +0000926 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Evan Cheng30729b42007-09-17 22:26:41 +0000927 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000928 InFlagDecled, ResNodeDecled);
929 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
930 ++ChildNo;
931 } else {
Evan Chenga9559392007-07-06 01:05:26 +0000932 // Otherwise, this is a predicate or optional def operand, emit the
933 // 'default ops' operands.
934 const DAGDefaultOperand &DefaultOp =
Chris Lattner6cefb772008-01-05 22:25:12 +0000935 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Evan Chenga9559392007-07-06 01:05:26 +0000936 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Cheng30729b42007-09-17 22:26:41 +0000937 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000938 InFlagDecled, ResNodeDecled);
939 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Evan Cheng39376d02007-05-15 01:19:51 +0000940 NumEAInputs += Ops.size();
Chris Lattnerefe9f4a2006-11-04 05:12:02 +0000941 }
942 }
Evan Chengb915f312005-12-09 22:45:35 +0000943 }
944
Dan Gohmanc6c391d2008-01-31 00:25:39 +0000945 // Generate MemOperandSDNodes nodes for each memory accesses covered by this
946 // pattern.
947 if (isRoot) {
948 std::vector<std::string>::const_iterator mi, mie;
949 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
950 emitCode("SDOperand LSI_" + *mi + " = "
951 "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
952 *mi + ")->getMemOperand());");
953 AllOps.push_back("LSI_" + *mi);
954 }
955 }
956
Evan Chengb915f312005-12-09 22:45:35 +0000957 // Emit all the chain and CopyToReg stuff.
Evan Cheng045953c2006-05-10 00:05:46 +0000958 bool ChainEmitted = NodeHasChain;
959 if (NodeHasChain)
Evan Cheng676d7312006-08-26 00:59:04 +0000960 emitCode("AddToISelQueue(" + ChainName + ");");
Evan Chengbc6b86a2006-06-14 19:27:50 +0000961 if (NodeHasInFlag || HasImpInputs)
Evan Cheng676d7312006-08-26 00:59:04 +0000962 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
963 InFlagDecled, ResNodeDecled, true);
Evan Chengf037ca62006-08-27 08:11:28 +0000964 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
Evan Cheng676d7312006-08-26 00:59:04 +0000965 if (!InFlagDecled) {
966 emitCode("SDOperand InFlag(0, 0);");
967 InFlagDecled = true;
968 }
Evan Chengf037ca62006-08-27 08:11:28 +0000969 if (NodeHasOptInFlag) {
970 emitCode("if (HasInFlag) {");
971 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
972 emitCode(" AddToISelQueue(InFlag);");
973 emitCode("}");
974 }
Evan Chengbc6b86a2006-06-14 19:27:50 +0000975 }
Evan Chengb915f312005-12-09 22:45:35 +0000976
Evan Chengb915f312005-12-09 22:45:35 +0000977 unsigned ResNo = TmpNo++;
Evan Cheng3eff89b2006-05-10 02:47:57 +0000978 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
Evan Chengef61ed32007-09-07 23:59:02 +0000979 NodeHasOptInFlag || HasImpResults) {
Evan Chenge945f4d2006-06-14 22:22:20 +0000980 std::string Code;
981 std::string Code2;
982 std::string NodeName;
983 if (!isRoot) {
984 NodeName = "Tmp" + utostr(ResNo);
Dan Gohmana6a1ab32007-07-24 22:58:00 +0000985 Code2 = "SDOperand " + NodeName + "(";
Evan Cheng9789aaa2006-01-24 20:46:50 +0000986 } else {
Evan Chenge945f4d2006-06-14 22:22:20 +0000987 NodeName = "ResNode";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +0000988 if (!ResNodeDecled) {
Evan Cheng676d7312006-08-26 00:59:04 +0000989 Code2 = "SDNode *" + NodeName + " = ";
Lauro Ramos Venancio195c6c22007-04-26 17:03:22 +0000990 ResNodeDecled = true;
991 } else
Evan Cheng676d7312006-08-26 00:59:04 +0000992 Code2 = NodeName + " = ";
Evan Chengbcecf332005-12-17 01:19:28 +0000993 }
Evan Chengf037ca62006-08-27 08:11:28 +0000994
Evan Cheng85dbe1a2007-09-12 23:30:14 +0000995 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Evan Chengf037ca62006-08-27 08:11:28 +0000996 unsigned OpsNo = OpcNo;
Evan Chengfceb57a2006-07-15 08:45:20 +0000997 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
Evan Chenge945f4d2006-06-14 22:22:20 +0000998
999 // Output order: results, chain, flags
1000 // Result types.
Evan Chengf8729402006-07-16 06:12:52 +00001001 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1002 Code += ", VT" + utostr(VTNo);
1003 emitVT(getEnumName(N->getTypeNum(0)));
1004 }
Evan Chengef61ed32007-09-07 23:59:02 +00001005 // Add types for implicit results in physical registers, scheduler will
1006 // care of adding copyfromreg nodes.
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001007 for (unsigned i = 0; i < NumDstRegs; i++) {
1008 Record *RR = DstRegs[i];
1009 if (RR->isSubClassOf("Register")) {
1010 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1011 Code += ", " + getEnumName(RVT);
Evan Chengef61ed32007-09-07 23:59:02 +00001012 }
1013 }
Evan Chenge945f4d2006-06-14 22:22:20 +00001014 if (NodeHasChain)
1015 Code += ", MVT::Other";
1016 if (NodeHasOutFlag)
1017 Code += ", MVT::Flag";
1018
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001019 // Figure out how many fixed inputs the node has. This is important to
1020 // know which inputs are the variable ones if present.
1021 unsigned NumInputs = AllOps.size();
1022 NumInputs += NodeHasChain;
1023
Evan Chenge945f4d2006-06-14 22:22:20 +00001024 // Inputs.
Evan Chengf037ca62006-08-27 08:11:28 +00001025 if (HasVarOps) {
1026 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1027 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1028 AllOps.clear();
Evan Chenge945f4d2006-06-14 22:22:20 +00001029 }
1030
1031 if (HasVarOps) {
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001032 // Figure out whether any operands at the end of the op list are not
1033 // part of the variable section.
1034 std::string EndAdjust;
Evan Chenge945f4d2006-06-14 22:22:20 +00001035 if (NodeHasInFlag || HasImpInputs)
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001036 EndAdjust = "-1"; // Always has one flag.
1037 else if (NodeHasOptInFlag)
1038 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1039
Evan Cheng39376d02007-05-15 01:19:51 +00001040 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
Chris Lattner7c3a96b2006-11-14 18:41:38 +00001041 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1042
Evan Cheng676d7312006-08-26 00:59:04 +00001043 emitCode(" AddToISelQueue(N.getOperand(i));");
Evan Chengf037ca62006-08-27 08:11:28 +00001044 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
Evan Chenge945f4d2006-06-14 22:22:20 +00001045 emitCode("}");
1046 }
1047
1048 if (NodeHasChain) {
1049 if (HasVarOps)
Evan Chengf037ca62006-08-27 08:11:28 +00001050 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00001051 else
Evan Chengf037ca62006-08-27 08:11:28 +00001052 AllOps.push_back(ChainName);
Evan Chenge945f4d2006-06-14 22:22:20 +00001053 }
1054
Evan Chengf037ca62006-08-27 08:11:28 +00001055 if (HasVarOps) {
1056 if (NodeHasInFlag || HasImpInputs)
1057 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1058 else if (NodeHasOptInFlag) {
1059 emitCode("if (HasInFlag)");
1060 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1061 }
1062 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1063 ".size()";
1064 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001065 AllOps.push_back("InFlag");
Evan Chenge945f4d2006-06-14 22:22:20 +00001066
Evan Chengf037ca62006-08-27 08:11:28 +00001067 unsigned NumOps = AllOps.size();
1068 if (NumOps) {
1069 if (!NodeHasOptInFlag && NumOps < 4) {
1070 for (unsigned i = 0; i != NumOps; ++i)
1071 Code += ", " + AllOps[i];
1072 } else {
1073 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1074 for (unsigned i = 0; i != NumOps; ++i) {
1075 OpsCode += AllOps[i];
1076 if (i != NumOps-1)
1077 OpsCode += ", ";
1078 }
1079 emitCode(OpsCode + " };");
1080 Code += ", Ops" + utostr(OpsNo) + ", ";
1081 if (NodeHasOptInFlag) {
1082 Code += "HasInFlag ? ";
1083 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1084 } else
1085 Code += utostr(NumOps);
1086 }
1087 }
1088
Evan Chenge945f4d2006-06-14 22:22:20 +00001089 if (!isRoot)
1090 Code += "), 0";
1091 emitCode(Code2 + Code + ");");
1092
1093 if (NodeHasChain)
1094 // Remember which op produces the chain.
1095 if (!isRoot)
1096 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001097 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
Evan Chenge945f4d2006-06-14 22:22:20 +00001098 else
1099 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001100 ", " + utostr(NumResults+NumDstRegs) + ");");
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001101
Evan Cheng676d7312006-08-26 00:59:04 +00001102 if (!isRoot) {
1103 NodeOps.push_back("Tmp" + utostr(ResNo));
1104 return NodeOps;
1105 }
Evan Cheng045953c2006-05-10 00:05:46 +00001106
Evan Cheng06d64702006-08-11 08:59:35 +00001107 bool NeedReplace = false;
Evan Cheng676d7312006-08-26 00:59:04 +00001108 if (NodeHasOutFlag) {
1109 if (!InFlagDecled) {
Dan Gohmana6a1ab32007-07-24 22:58:00 +00001110 emitCode("SDOperand InFlag(ResNode, " +
Evan Cheng30729b42007-09-17 22:26:41 +00001111 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00001112 InFlagDecled = true;
1113 } else
1114 emitCode("InFlag = SDOperand(ResNode, " +
Evan Cheng30729b42007-09-17 22:26:41 +00001115 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00001116 }
Evan Cheng4fba2812005-12-20 07:37:41 +00001117
Evan Cheng97938882005-12-22 02:24:50 +00001118 if (FoldedChains.size() > 0) {
Chris Lattner8a0604b2006-01-28 20:31:24 +00001119 std::string Code;
Evan Cheng1b80f4d2005-12-19 07:18:51 +00001120 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
Chris Lattner706d2d32006-08-09 16:44:44 +00001121 emitCode("ReplaceUses(SDOperand(" +
Evan Cheng67212a02006-02-09 22:12:27 +00001122 FoldedChains[j].first + ".Val, " +
Chris Lattner706d2d32006-08-09 16:44:44 +00001123 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001124 utostr(NumResults+NumDstRegs) + "));");
Evan Cheng06d64702006-08-11 08:59:35 +00001125 NeedReplace = true;
Evan Chengb915f312005-12-09 22:45:35 +00001126 }
Evan Chengf9fc25d2005-12-19 22:40:04 +00001127
Evan Cheng06d64702006-08-11 08:59:35 +00001128 if (NodeHasOutFlag) {
Chris Lattner706d2d32006-08-09 16:44:44 +00001129 emitCode("ReplaceUses(SDOperand(N.Val, " +
Evan Cheng30729b42007-09-17 22:26:41 +00001130 utostr(NumPatResults + (unsigned)InputHasChain)
1131 +"), InFlag);");
Evan Cheng06d64702006-08-11 08:59:35 +00001132 NeedReplace = true;
1133 }
1134
Evan Cheng30729b42007-09-17 22:26:41 +00001135 if (NeedReplace && InputHasChain)
1136 emitCode("ReplaceUses(SDOperand(N.Val, " +
1137 utostr(NumPatResults) + "), SDOperand(" + ChainName
1138 + ".Val, " + ChainName + ".ResNo" + "));");
Evan Cheng97938882005-12-22 02:24:50 +00001139
Evan Chenged66e852006-03-09 08:19:11 +00001140 // User does not expect the instruction would produce a chain!
Evan Cheng06d64702006-08-11 08:59:35 +00001141 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
Evan Cheng9ade2182006-08-26 05:34:46 +00001142 ;
Evan Cheng3eff89b2006-05-10 02:47:57 +00001143 } else if (InputHasChain && !NodeHasChain) {
1144 // One of the inner node produces a chain.
Evan Cheng9ade2182006-08-26 05:34:46 +00001145 if (NodeHasOutFlag)
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001146 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
Evan Cheng06d64702006-08-11 08:59:35 +00001147 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001148 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
Evan Cheng06d64702006-08-11 08:59:35 +00001149 "), " + ChainName + ");");
Evan Cheng4fba2812005-12-20 07:37:41 +00001150 }
Evan Cheng06d64702006-08-11 08:59:35 +00001151
Evan Cheng30729b42007-09-17 22:26:41 +00001152 emitCode("return ResNode;");
Evan Chengb915f312005-12-09 22:45:35 +00001153 } else {
Evan Cheng9ade2182006-08-26 05:34:46 +00001154 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
Evan Chengfceb57a2006-07-15 08:45:20 +00001155 utostr(OpcNo);
Nate Begemanb73628b2005-12-30 00:12:56 +00001156 if (N->getTypeNum(0) != MVT::isVoid)
Evan Chengf8729402006-07-16 06:12:52 +00001157 Code += ", VT" + utostr(VTNo);
Evan Cheng54597732006-01-26 00:22:25 +00001158 if (NodeHasOutFlag)
Chris Lattner8a0604b2006-01-28 20:31:24 +00001159 Code += ", MVT::Flag";
Evan Chengf037ca62006-08-27 08:11:28 +00001160
1161 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1162 AllOps.push_back("InFlag");
1163
1164 unsigned NumOps = AllOps.size();
1165 if (NumOps) {
1166 if (!NodeHasOptInFlag && NumOps < 4) {
1167 for (unsigned i = 0; i != NumOps; ++i)
1168 Code += ", " + AllOps[i];
1169 } else {
1170 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1171 for (unsigned i = 0; i != NumOps; ++i) {
1172 OpsCode += AllOps[i];
1173 if (i != NumOps-1)
1174 OpsCode += ", ";
1175 }
1176 emitCode(OpsCode + " };");
1177 Code += ", Ops" + utostr(OpcNo) + ", ";
1178 Code += utostr(NumOps);
1179 }
1180 }
Evan Cheng95514ba2006-08-26 08:00:10 +00001181 emitCode(Code + ");");
Evan Cheng676d7312006-08-26 00:59:04 +00001182 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1183 if (N->getTypeNum(0) != MVT::isVoid)
1184 emitVT(getEnumName(N->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00001185 }
Evan Cheng4fba2812005-12-20 07:37:41 +00001186
Evan Cheng676d7312006-08-26 00:59:04 +00001187 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00001188 } else if (Op->isSubClassOf("SDNodeXForm")) {
1189 assert(N->getNumChildren() == 1 && "node xform should have one child!");
Evan Cheng863bf5a2006-03-20 22:53:06 +00001190 // PatLeaf node - the operand may or may not be a leaf node. But it should
1191 // behave like one.
Evan Cheng676d7312006-08-26 00:59:04 +00001192 std::vector<std::string> Ops =
Evan Cheng30729b42007-09-17 22:26:41 +00001193 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Evan Cheng676d7312006-08-26 00:59:04 +00001194 ResNodeDecled, true);
Evan Chengb915f312005-12-09 22:45:35 +00001195 unsigned ResNo = TmpNo++;
Evan Cheng676d7312006-08-26 00:59:04 +00001196 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1197 + "(" + Ops.back() + ".Val);");
1198 NodeOps.push_back("Tmp" + utostr(ResNo));
Evan Cheng9ade2182006-08-26 05:34:46 +00001199 if (isRoot)
1200 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00001201 return NodeOps;
Evan Chengb915f312005-12-09 22:45:35 +00001202 } else {
1203 N->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001204 cerr << "\n";
Chris Lattner7893f132006-01-11 01:33:49 +00001205 throw std::string("Unknown node in result pattern!");
Evan Chengb915f312005-12-09 22:45:35 +00001206 }
1207 }
1208
Chris Lattner488580c2006-01-28 19:06:51 +00001209 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1210 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
Evan Chengb915f312005-12-09 22:45:35 +00001211 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1212 /// for, this returns true otherwise false if Pat has all types.
1213 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
Chris Lattner706d2d32006-08-09 16:44:44 +00001214 const std::string &Prefix, bool isRoot = false) {
Evan Chengb915f312005-12-09 22:45:35 +00001215 // Did we find one?
Evan Chengd15531b2006-05-19 07:24:32 +00001216 if (Pat->getExtTypes() != Other->getExtTypes()) {
Evan Chengb915f312005-12-09 22:45:35 +00001217 // Move a type over from 'other' to 'pat'.
Nate Begemanb73628b2005-12-30 00:12:56 +00001218 Pat->setTypes(Other->getExtTypes());
Chris Lattner706d2d32006-08-09 16:44:44 +00001219 // The top level node type is checked outside of the select function.
1220 if (!isRoot)
1221 emitCheck(Prefix + ".Val->getValueType(0) == " +
1222 getName(Pat->getTypeNum(0)));
Evan Chengb915f312005-12-09 22:45:35 +00001223 return true;
Evan Chengb915f312005-12-09 22:45:35 +00001224 }
1225
Evan Cheng51fecc82006-01-09 18:27:06 +00001226 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +00001227 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Evan Chengb915f312005-12-09 22:45:35 +00001228 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1229 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1230 Prefix + utostr(OpNo)))
1231 return true;
1232 return false;
1233 }
1234
1235private:
Evan Cheng54597732006-01-26 00:22:25 +00001236 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
Evan Chengb915f312005-12-09 22:45:35 +00001237 /// being built.
Evan Cheng54597732006-01-26 00:22:25 +00001238 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
Evan Cheng676d7312006-08-26 00:59:04 +00001239 bool &ChainEmitted, bool &InFlagDecled,
1240 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001241 const CodeGenTarget &T = CGP.getTargetInfo();
Evan Cheng51fecc82006-01-09 18:27:06 +00001242 unsigned OpNo =
Chris Lattner6cefb772008-01-05 22:25:12 +00001243 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1244 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Evan Chengb915f312005-12-09 22:45:35 +00001245 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1246 TreePatternNode *Child = N->getChild(i);
1247 if (!Child->isLeaf()) {
Evan Cheng676d7312006-08-26 00:59:04 +00001248 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1249 InFlagDecled, ResNodeDecled);
Evan Chengb915f312005-12-09 22:45:35 +00001250 } else {
1251 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
Evan Chengb4ad33c2006-01-19 01:55:45 +00001252 if (!Child->getName().empty()) {
1253 std::string Name = RootName + utostr(OpNo);
1254 if (Duplicates.find(Name) != Duplicates.end())
1255 // A duplicate! Do not emit a copy for this node.
1256 continue;
1257 }
1258
Evan Chengb915f312005-12-09 22:45:35 +00001259 Record *RR = DI->getDef();
1260 if (RR->isSubClassOf("Register")) {
1261 MVT::ValueType RVT = getRegisterValueType(RR, T);
Evan Chengbcecf332005-12-17 01:19:28 +00001262 if (RVT == MVT::Flag) {
Evan Cheng676d7312006-08-26 00:59:04 +00001263 if (!InFlagDecled) {
1264 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1265 InFlagDecled = true;
1266 } else
1267 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1268 emitCode("AddToISelQueue(InFlag);");
Evan Chengb2c6d492006-01-11 22:16:13 +00001269 } else {
1270 if (!ChainEmitted) {
Evan Cheng676d7312006-08-26 00:59:04 +00001271 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
Evan Chenge4a8a6e2006-02-03 06:22:41 +00001272 ChainName = "Chain";
Evan Chengb2c6d492006-01-11 22:16:13 +00001273 ChainEmitted = true;
1274 }
Evan Cheng676d7312006-08-26 00:59:04 +00001275 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1276 if (!InFlagDecled) {
1277 emitCode("SDOperand InFlag(0, 0);");
1278 InFlagDecled = true;
1279 }
1280 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1281 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner6cefb772008-01-05 22:25:12 +00001282 ", " + getQualifiedName(RR) +
Evan Cheng7a33db02006-08-26 07:39:28 +00001283 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
Evan Cheng676d7312006-08-26 00:59:04 +00001284 ResNodeDecled = true;
Evan Cheng67212a02006-02-09 22:12:27 +00001285 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1286 emitCode("InFlag = SDOperand(ResNode, 1);");
Evan Chengb915f312005-12-09 22:45:35 +00001287 }
1288 }
1289 }
1290 }
1291 }
Evan Cheng54597732006-01-26 00:22:25 +00001292
Evan Cheng676d7312006-08-26 00:59:04 +00001293 if (HasInFlag) {
1294 if (!InFlagDecled) {
1295 emitCode("SDOperand InFlag = " + RootName +
1296 ".getOperand(" + utostr(OpNo) + ");");
1297 InFlagDecled = true;
1298 } else
1299 emitCode("InFlag = " + RootName +
1300 ".getOperand(" + utostr(OpNo) + ");");
1301 emitCode("AddToISelQueue(InFlag);");
1302 }
Evan Chengb915f312005-12-09 22:45:35 +00001303 }
1304};
1305
Chris Lattnerd1ff35a2005-09-23 21:33:23 +00001306/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1307/// stream to match the pattern, and generate the code for the match if it
Chris Lattner355408b2006-01-29 02:43:35 +00001308/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner60d81392008-01-05 22:30:17 +00001309void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Evan Cheng676d7312006-08-26 00:59:04 +00001310 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
Evan Chengf5493192006-08-26 01:02:19 +00001311 std::set<std::string> &GeneratedDecl,
Evan Chengfceb57a2006-07-15 08:45:20 +00001312 std::vector<std::string> &TargetOpcodes,
Evan Chengf5493192006-08-26 01:02:19 +00001313 std::vector<std::string> &TargetVTs) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001314 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
Evan Cheng58e84a62005-12-14 22:02:59 +00001315 Pattern.getSrcPattern(), Pattern.getDstPattern(),
Evan Chengf8729402006-07-16 06:12:52 +00001316 GeneratedCode, GeneratedDecl,
Chris Lattner706d2d32006-08-09 16:44:44 +00001317 TargetOpcodes, TargetVTs);
Evan Chengb915f312005-12-09 22:45:35 +00001318
Chris Lattner8fc35682005-09-23 23:16:51 +00001319 // Emit the matcher, capturing named arguments in VariableMap.
Evan Cheng7b05bd52005-12-23 22:11:47 +00001320 bool FoundChain = false;
Evan Cheng13e9e9c2006-10-16 06:33:44 +00001321 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
Evan Chengb915f312005-12-09 22:45:35 +00001322
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001323 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner200c57e2008-01-05 22:58:54 +00001324 TreePattern &TP = *CGP.pf_begin()->second;
Chris Lattner296dfe32005-09-24 00:50:51 +00001325
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001326 // At this point, we know that we structurally match the pattern, but the
1327 // types of the nodes may not match. Figure out the fewest number of type
1328 // comparisons we need to emit. For example, if there is only one integer
1329 // type supported by a target, there should be no type comparisons at all for
1330 // integer patterns!
1331 //
1332 // To figure out the fewest number of type checks needed, clone the pattern,
1333 // remove the types, then perform type inference on the pattern as a whole.
1334 // If there are unresolved types, emit an explicit check for those types,
1335 // apply the type to the tree, then rerun type inference. Iterate until all
1336 // types are resolved.
1337 //
Evan Cheng58e84a62005-12-14 22:02:59 +00001338 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001339 RemoveAllTypes(Pat);
Chris Lattner7e82f132005-10-15 21:34:21 +00001340
1341 do {
1342 // Resolve/propagate as many types as possible.
1343 try {
1344 bool MadeChange = true;
1345 while (MadeChange)
Chris Lattner488580c2006-01-28 19:06:51 +00001346 MadeChange = Pat->ApplyTypeConstraints(TP,
1347 true/*Ignore reg constraints*/);
Chris Lattner7e82f132005-10-15 21:34:21 +00001348 } catch (...) {
1349 assert(0 && "Error: could not find consistent types for something we"
1350 " already decided was ok!");
1351 abort();
1352 }
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001353
Chris Lattner7e82f132005-10-15 21:34:21 +00001354 // Insert a check for an unresolved type and add it to the tree. If we find
1355 // an unresolved type to add a check for, this returns true and we iterate,
1356 // otherwise we are done.
Chris Lattner706d2d32006-08-09 16:44:44 +00001357 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
Evan Cheng1c3d19e2005-12-04 08:18:16 +00001358
Evan Cheng85dbe1a2007-09-12 23:30:14 +00001359 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Cheng30729b42007-09-17 22:26:41 +00001360 false, false, false, true);
Chris Lattner0ee7cff2005-10-14 04:11:13 +00001361 delete Pat;
Chris Lattner3f7e9142005-09-23 20:52:47 +00001362}
1363
Chris Lattner24e00a42006-01-29 04:41:05 +00001364/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1365/// a line causes any of them to be empty, remove them and return true when
1366/// done.
Chris Lattner60d81392008-01-05 22:30:17 +00001367static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001368 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner24e00a42006-01-29 04:41:05 +00001369 &Patterns) {
1370 bool ErasedPatterns = false;
1371 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1372 Patterns[i].second.pop_back();
1373 if (Patterns[i].second.empty()) {
1374 Patterns.erase(Patterns.begin()+i);
1375 --i; --e;
1376 ErasedPatterns = true;
1377 }
1378 }
1379 return ErasedPatterns;
1380}
1381
Chris Lattner8bc74722006-01-29 04:25:26 +00001382/// EmitPatterns - Emit code for at least one pattern, but try to group common
1383/// code together between the patterns.
Chris Lattner60d81392008-01-05 22:30:17 +00001384void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Evan Cheng676d7312006-08-26 00:59:04 +00001385 std::vector<std::pair<unsigned, std::string> > > >
Chris Lattner8bc74722006-01-29 04:25:26 +00001386 &Patterns, unsigned Indent,
1387 std::ostream &OS) {
Evan Cheng676d7312006-08-26 00:59:04 +00001388 typedef std::pair<unsigned, std::string> CodeLine;
Chris Lattner8bc74722006-01-29 04:25:26 +00001389 typedef std::vector<CodeLine> CodeList;
Chris Lattner60d81392008-01-05 22:30:17 +00001390 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Chris Lattner8bc74722006-01-29 04:25:26 +00001391
1392 if (Patterns.empty()) return;
1393
Chris Lattner24e00a42006-01-29 04:41:05 +00001394 // Figure out how many patterns share the next code line. Explicitly copy
1395 // FirstCodeLine so that we don't invalidate a reference when changing
1396 // Patterns.
1397 const CodeLine FirstCodeLine = Patterns.back().second.back();
Chris Lattner8bc74722006-01-29 04:25:26 +00001398 unsigned LastMatch = Patterns.size()-1;
1399 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1400 --LastMatch;
1401
1402 // If not all patterns share this line, split the list into two pieces. The
1403 // first chunk will use this line, the second chunk won't.
1404 if (LastMatch != 0) {
1405 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1406 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1407
1408 // FIXME: Emit braces?
1409 if (Shared.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001410 const PatternToMatch &Pattern = *Shared.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001411 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1412 Pattern.getSrcPattern()->print(OS);
1413 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1414 Pattern.getDstPattern()->print(OS);
1415 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001416 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001417 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001418 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001419 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001420 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Evan Chenge6f32032006-07-19 00:24:41 +00001421 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001422 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001423 }
Evan Cheng676d7312006-08-26 00:59:04 +00001424 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001425 OS << std::string(Indent, ' ') << "{\n";
1426 Indent += 2;
1427 }
1428 EmitPatterns(Shared, Indent, OS);
Evan Cheng676d7312006-08-26 00:59:04 +00001429 if (FirstCodeLine.first != 1) {
Chris Lattner8bc74722006-01-29 04:25:26 +00001430 Indent -= 2;
1431 OS << std::string(Indent, ' ') << "}\n";
1432 }
1433
1434 if (Other.size() == 1) {
Chris Lattner60d81392008-01-05 22:30:17 +00001435 const PatternToMatch &Pattern = *Other.back().first;
Chris Lattner8bc74722006-01-29 04:25:26 +00001436 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1437 Pattern.getSrcPattern()->print(OS);
1438 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1439 Pattern.getDstPattern()->print(OS);
1440 OS << "\n";
Evan Chengc81d2a02006-04-19 20:36:09 +00001441 unsigned AddedComplexity = Pattern.getAddedComplexity();
Chris Lattner8bc74722006-01-29 04:25:26 +00001442 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001443 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Evan Cheng59413202006-04-19 18:07:24 +00001444 << " cost = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001445 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Chris Lattner706d2d32006-08-09 16:44:44 +00001446 << " size = "
Chris Lattner200c57e2008-01-05 22:58:54 +00001447 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Chris Lattner8bc74722006-01-29 04:25:26 +00001448 }
1449 EmitPatterns(Other, Indent, OS);
1450 return;
1451 }
1452
Chris Lattner24e00a42006-01-29 04:41:05 +00001453 // Remove this code from all of the patterns that share it.
1454 bool ErasedPatterns = EraseCodeLine(Patterns);
1455
Evan Cheng676d7312006-08-26 00:59:04 +00001456 bool isPredicate = FirstCodeLine.first == 1;
Chris Lattner8bc74722006-01-29 04:25:26 +00001457
1458 // Otherwise, every pattern in the list has this line. Emit it.
1459 if (!isPredicate) {
1460 // Normal code.
1461 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1462 } else {
Chris Lattner24e00a42006-01-29 04:41:05 +00001463 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1464
1465 // If the next code line is another predicate, and if all of the pattern
1466 // in this group share the same next line, emit it inline now. Do this
1467 // until we run out of common predicates.
Evan Cheng676d7312006-08-26 00:59:04 +00001468 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Chris Lattner24e00a42006-01-29 04:41:05 +00001469 // Check that all of fhe patterns in Patterns end with the same predicate.
1470 bool AllEndWithSamePredicate = true;
1471 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1472 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1473 AllEndWithSamePredicate = false;
1474 break;
1475 }
1476 // If all of the predicates aren't the same, we can't share them.
1477 if (!AllEndWithSamePredicate) break;
1478
1479 // Otherwise we can. Emit it shared now.
1480 OS << " &&\n" << std::string(Indent+4, ' ')
1481 << Patterns.back().second.back().second;
1482 ErasedPatterns = EraseCodeLine(Patterns);
Chris Lattner8bc74722006-01-29 04:25:26 +00001483 }
Chris Lattner24e00a42006-01-29 04:41:05 +00001484
1485 OS << ") {\n";
1486 Indent += 2;
Chris Lattner8bc74722006-01-29 04:25:26 +00001487 }
1488
1489 EmitPatterns(Patterns, Indent, OS);
1490
1491 if (isPredicate)
1492 OS << std::string(Indent-2, ' ') << "}\n";
1493}
1494
Chris Lattnerfe718932008-01-06 01:10:31 +00001495static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
Chris Lattner6cefb772008-01-05 22:25:12 +00001496 return CGP.getSDNodeInfo(Op).getEnumName();
Evan Cheng892aaf82006-11-08 23:01:03 +00001497}
Chris Lattner8bc74722006-01-29 04:25:26 +00001498
Evan Cheng892aaf82006-11-08 23:01:03 +00001499static std::string getLegalCName(std::string OpName) {
1500 std::string::size_type pos = OpName.find("::");
1501 if (pos != std::string::npos)
1502 OpName.replace(pos, 2, "_");
1503 return OpName;
Chris Lattner37481472005-09-26 21:59:35 +00001504}
1505
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001506void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001507 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner6cefb772008-01-05 22:25:12 +00001508
Chris Lattnerf7560ed2006-11-20 18:54:33 +00001509 // Get the namespace to insert instructions into. Make sure not to pick up
1510 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1511 // instruction or something.
1512 std::string InstNS;
1513 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1514 e = Target.inst_end(); i != e; ++i) {
1515 InstNS = i->second.Namespace;
1516 if (InstNS != "TargetInstrInfo")
1517 break;
1518 }
1519
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001520 if (!InstNS.empty()) InstNS += "::";
1521
Chris Lattner602f6922006-01-04 00:25:00 +00001522 // Group the patterns by their top-level opcodes.
Chris Lattner60d81392008-01-05 22:30:17 +00001523 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Evan Chengfceb57a2006-07-15 08:45:20 +00001524 // All unique target node emission functions.
1525 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerfe718932008-01-06 01:10:31 +00001526 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001527 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner60d81392008-01-05 22:30:17 +00001528 const PatternToMatch &Pattern = *I;
Chris Lattner6cefb772008-01-05 22:25:12 +00001529
1530 TreePatternNode *Node = Pattern.getSrcPattern();
Chris Lattner602f6922006-01-04 00:25:00 +00001531 if (!Node->isLeaf()) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001532 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001533 push_back(&Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001534 } else {
1535 const ComplexPattern *CP;
Chris Lattner9c5d4de2006-11-03 01:11:05 +00001536 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001537 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner6cefb772008-01-05 22:25:12 +00001538 push_back(&Pattern);
Chris Lattner200c57e2008-01-05 22:58:54 +00001539 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Chris Lattner602f6922006-01-04 00:25:00 +00001540 std::vector<Record*> OpNodes = CP->getRootNodes();
1541 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001542 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1543 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner6cefb772008-01-05 22:25:12 +00001544 &Pattern);
Chris Lattner602f6922006-01-04 00:25:00 +00001545 }
1546 } else {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001547 cerr << "Unrecognized opcode '";
Chris Lattner602f6922006-01-04 00:25:00 +00001548 Node->dump();
Bill Wendlingf5da1332006-12-07 22:21:48 +00001549 cerr << "' on tree pattern '";
Chris Lattner6cefb772008-01-05 22:25:12 +00001550 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Chris Lattner602f6922006-01-04 00:25:00 +00001551 exit(1);
1552 }
1553 }
1554 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001555
1556 // For each opcode, there might be multiple select functions, one per
1557 // ValueType of the node (or its first operand if it doesn't produce a
1558 // non-chain result.
1559 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1560
Chris Lattner602f6922006-01-04 00:25:00 +00001561 // Emit one Select_* method for each top-level opcode. We do this instead of
1562 // emitting one giant switch statement to support compilers where this will
1563 // result in the recursive functions taking less stack space.
Chris Lattner60d81392008-01-05 22:30:17 +00001564 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001565 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1566 PBOI != E; ++PBOI) {
1567 const std::string &OpName = PBOI->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001568 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Chris Lattner706d2d32006-08-09 16:44:44 +00001569 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1570
Chris Lattner602f6922006-01-04 00:25:00 +00001571 // We want to emit all of the matching code now. However, we want to emit
1572 // the matches in order of minimal cost. Sort the patterns so the least
1573 // cost one is at the start.
Chris Lattner706d2d32006-08-09 16:44:44 +00001574 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner200c57e2008-01-05 22:58:54 +00001575 PatternSortingPredicate(CGP));
Evan Cheng21ad3922006-02-07 00:37:41 +00001576
Chris Lattner706d2d32006-08-09 16:44:44 +00001577 // Split them into groups by type.
Chris Lattner60d81392008-01-05 22:30:17 +00001578 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
Chris Lattner706d2d32006-08-09 16:44:44 +00001579 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner60d81392008-01-05 22:30:17 +00001580 const PatternToMatch *Pat = PatternsOfOp[i];
Chris Lattner706d2d32006-08-09 16:44:44 +00001581 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner706d2d32006-08-09 16:44:44 +00001582 MVT::ValueType VT = SrcPat->getTypeNum(0);
Chris Lattner60d81392008-01-05 22:30:17 +00001583 std::map<MVT::ValueType,
1584 std::vector<const PatternToMatch*> >::iterator TI =
Chris Lattner706d2d32006-08-09 16:44:44 +00001585 PatternsByType.find(VT);
1586 if (TI != PatternsByType.end())
1587 TI->second.push_back(Pat);
1588 else {
Chris Lattner60d81392008-01-05 22:30:17 +00001589 std::vector<const PatternToMatch*> PVec;
Chris Lattner706d2d32006-08-09 16:44:44 +00001590 PVec.push_back(Pat);
1591 PatternsByType.insert(std::make_pair(VT, PVec));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001592 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001593 }
1594
Chris Lattner60d81392008-01-05 22:30:17 +00001595 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001596 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1597 ++II) {
1598 MVT::ValueType OpVT = II->first;
Chris Lattner60d81392008-01-05 22:30:17 +00001599 std::vector<const PatternToMatch*> &Patterns = II->second;
Chris Lattner64906972006-09-21 18:28:27 +00001600 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1601 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
Chris Lattner706d2d32006-08-09 16:44:44 +00001602
Chris Lattner60d81392008-01-05 22:30:17 +00001603 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Chris Lattner706d2d32006-08-09 16:44:44 +00001604 std::vector<std::vector<std::string> > PatternOpcodes;
1605 std::vector<std::vector<std::string> > PatternVTs;
Evan Chengf5493192006-08-26 01:02:19 +00001606 std::vector<std::set<std::string> > PatternDecls;
Chris Lattner706d2d32006-08-09 16:44:44 +00001607 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1608 CodeList GeneratedCode;
Evan Chengf5493192006-08-26 01:02:19 +00001609 std::set<std::string> GeneratedDecl;
Chris Lattner706d2d32006-08-09 16:44:44 +00001610 std::vector<std::string> TargetOpcodes;
1611 std::vector<std::string> TargetVTs;
1612 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1613 TargetOpcodes, TargetVTs);
Chris Lattner706d2d32006-08-09 16:44:44 +00001614 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1615 PatternDecls.push_back(GeneratedDecl);
1616 PatternOpcodes.push_back(TargetOpcodes);
1617 PatternVTs.push_back(TargetVTs);
1618 }
1619
1620 // Scan the code to see if all of the patterns are reachable and if it is
1621 // possible that the last one might not match.
1622 bool mightNotMatch = true;
1623 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1624 CodeList &GeneratedCode = CodeForPatterns[i].second;
1625 mightNotMatch = false;
1626
1627 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001628 if (GeneratedCode[j].first == 1) { // predicate.
Chris Lattner706d2d32006-08-09 16:44:44 +00001629 mightNotMatch = true;
1630 break;
1631 }
1632 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001633
Chris Lattner706d2d32006-08-09 16:44:44 +00001634 // If this pattern definitely matches, and if it isn't the last one, the
1635 // patterns after it CANNOT ever match. Error out.
1636 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001637 cerr << "Pattern '";
1638 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1639 cerr << "' is impossible to select!\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001640 exit(1);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001641 }
1642 }
1643
Chris Lattner706d2d32006-08-09 16:44:44 +00001644 // Factor target node emission code (emitted by EmitResultCode) into
1645 // separate functions. Uniquing and share them among all instruction
1646 // selection routines.
1647 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1648 CodeList &GeneratedCode = CodeForPatterns[i].second;
1649 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1650 std::vector<std::string> &TargetVTs = PatternVTs[i];
Evan Chengf5493192006-08-26 01:02:19 +00001651 std::set<std::string> Decls = PatternDecls[i];
Evan Cheng676d7312006-08-26 00:59:04 +00001652 std::vector<std::string> AddedInits;
Chris Lattner706d2d32006-08-09 16:44:44 +00001653 int CodeSize = (int)GeneratedCode.size();
1654 int LastPred = -1;
1655 for (int j = CodeSize-1; j >= 0; --j) {
Evan Cheng676d7312006-08-26 00:59:04 +00001656 if (LastPred == -1 && GeneratedCode[j].first == 1)
Chris Lattner706d2d32006-08-09 16:44:44 +00001657 LastPred = j;
Evan Cheng676d7312006-08-26 00:59:04 +00001658 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1659 AddedInits.push_back(GeneratedCode[j].second);
Chris Lattner706d2d32006-08-09 16:44:44 +00001660 }
1661
Evan Cheng9ade2182006-08-26 05:34:46 +00001662 std::string CalleeCode = "(const SDOperand &N";
1663 std::string CallerCode = "(N";
Chris Lattner706d2d32006-08-09 16:44:44 +00001664 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1665 CalleeCode += ", unsigned Opc" + utostr(j);
1666 CallerCode += ", " + TargetOpcodes[j];
1667 }
1668 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1669 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1670 CallerCode += ", " + TargetVTs[j];
1671 }
Evan Chengf5493192006-08-26 01:02:19 +00001672 for (std::set<std::string>::iterator
Chris Lattner706d2d32006-08-09 16:44:44 +00001673 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
Evan Chengf5493192006-08-26 01:02:19 +00001674 std::string Name = *I;
Evan Cheng676d7312006-08-26 00:59:04 +00001675 CalleeCode += ", SDOperand &" + Name;
1676 CallerCode += ", " + Name;
Chris Lattner706d2d32006-08-09 16:44:44 +00001677 }
1678 CallerCode += ");";
1679 CalleeCode += ") ";
1680 // Prevent emission routines from being inlined to reduce selection
1681 // routines stack frame sizes.
Chris Lattner8dc728e2006-08-27 13:16:24 +00001682 CalleeCode += "DISABLE_INLINE ";
Evan Cheng676d7312006-08-26 00:59:04 +00001683 CalleeCode += "{\n";
1684
1685 for (std::vector<std::string>::const_reverse_iterator
1686 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1687 CalleeCode += " " + *I + "\n";
1688
Evan Chengf5493192006-08-26 01:02:19 +00001689 for (int j = LastPred+1; j < CodeSize; ++j)
1690 CalleeCode += " " + GeneratedCode[j].second + "\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001691 for (int j = LastPred+1; j < CodeSize; ++j)
1692 GeneratedCode.pop_back();
1693 CalleeCode += "}\n";
1694
1695 // Uniquing the emission routines.
1696 unsigned EmitFuncNum;
1697 std::map<std::string, unsigned>::iterator EFI =
1698 EmitFunctions.find(CalleeCode);
1699 if (EFI != EmitFunctions.end()) {
1700 EmitFuncNum = EFI->second;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001701 } else {
Chris Lattner706d2d32006-08-09 16:44:44 +00001702 EmitFuncNum = EmitFunctions.size();
1703 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Evan Cheng06d64702006-08-11 08:59:35 +00001704 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001705 }
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001706
Chris Lattner706d2d32006-08-09 16:44:44 +00001707 // Replace the emission code within selection routines with calls to the
1708 // emission functions.
Evan Cheng06d64702006-08-11 08:59:35 +00001709 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
Chris Lattner706d2d32006-08-09 16:44:44 +00001710 GeneratedCode.push_back(std::make_pair(false, CallerCode));
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001711 }
1712
Chris Lattner706d2d32006-08-09 16:44:44 +00001713 // Print function.
Chris Lattnerab51ddd2006-11-14 21:32:01 +00001714 std::string OpVTStr;
Chris Lattner33a40042006-11-14 22:17:10 +00001715 if (OpVT == MVT::iPTR) {
1716 OpVTStr = "_iPTR";
1717 } else if (OpVT == MVT::isVoid) {
1718 // Nodes with a void result actually have a first result type of either
1719 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1720 // void to this case, we handle it specially here.
1721 } else {
1722 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1723 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001724 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1725 OpcodeVTMap.find(OpName);
1726 if (OpVTI == OpcodeVTMap.end()) {
1727 std::vector<std::string> VTSet;
1728 VTSet.push_back(OpVTStr);
1729 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1730 } else
1731 OpVTI->second.push_back(OpVTStr);
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001732
Evan Cheng892aaf82006-11-08 23:01:03 +00001733 OS << "SDNode *Select_" << getLegalCName(OpName)
Chris Lattner33a40042006-11-14 22:17:10 +00001734 << OpVTStr << "(const SDOperand &N) {\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001735
Chris Lattner706d2d32006-08-09 16:44:44 +00001736 // Loop through and reverse all of the CodeList vectors, as we will be
1737 // accessing them from their logical front, but accessing the end of a
1738 // vector is more efficient.
1739 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1740 CodeList &GeneratedCode = CodeForPatterns[i].second;
1741 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001742 }
Chris Lattner706d2d32006-08-09 16:44:44 +00001743
1744 // Next, reverse the list of patterns itself for the same reason.
1745 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1746
1747 // Emit all of the patterns now, grouped together to share code.
1748 EmitPatterns(CodeForPatterns, 2, OS);
1749
Chris Lattner64906972006-09-21 18:28:27 +00001750 // If the last pattern has predicates (which could fail) emit code to
1751 // catch the case where nothing handles a pattern.
Chris Lattner706d2d32006-08-09 16:44:44 +00001752 if (mightNotMatch) {
Bill Wendlingf5da1332006-12-07 22:21:48 +00001753 OS << " cerr << \"Cannot yet select: \";\n";
Evan Cheng892aaf82006-11-08 23:01:03 +00001754 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1755 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1756 OpName != "ISD::INTRINSIC_VOID") {
Chris Lattner706d2d32006-08-09 16:44:44 +00001757 OS << " N.Val->dump(CurDAG);\n";
1758 } else {
1759 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1760 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001761 << " cerr << \"intrinsic %\"<< "
Chris Lattner706d2d32006-08-09 16:44:44 +00001762 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1763 }
Bill Wendlingf5da1332006-12-07 22:21:48 +00001764 OS << " cerr << '\\n';\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001765 << " abort();\n"
1766 << " return NULL;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001767 }
1768 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001769 }
Chris Lattner602f6922006-01-04 00:25:00 +00001770 }
1771
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001772 // Emit boilerplate.
Evan Cheng9ade2182006-08-26 05:34:46 +00001773 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001774 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00001775 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1776
1777 << " // Ensure that the asm operands are themselves selected.\n"
1778 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1779 << " AddToISelQueue(Ops[j]);\n\n"
1780
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001781 << " std::vector<MVT::ValueType> VTs;\n"
1782 << " VTs.push_back(MVT::Other);\n"
1783 << " VTs.push_back(MVT::Flag);\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00001784 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1785 "Ops.size());\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00001786 << " return New.Val;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001787 << "}\n\n";
1788
Jim Laskeya683f9b2007-01-26 17:29:20 +00001789 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1790 << " SDOperand Chain = N.getOperand(0);\n"
1791 << " SDOperand N1 = N.getOperand(1);\n"
Jim Laskey844b8922007-01-26 23:00:54 +00001792 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1793 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001794 << " AddToISelQueue(Chain);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001795 << " SDOperand Ops[] = { Tmp, Chain };\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001796 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001797 << " MVT::Other, Ops, 2);\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001798 << "}\n\n";
1799
Christopher Lamb08d52072007-07-26 07:48:21 +00001800 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1801 << " SDOperand N0 = N.getOperand(0);\n"
1802 << " SDOperand N1 = N.getOperand(1);\n"
1803 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1804 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1805 << " AddToISelQueue(N0);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001806 << " SDOperand Ops[] = { N0, Tmp };\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001807 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001808 << " N.getValueType(), Ops, 2);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001809 << "}\n\n";
1810
1811 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1812 << " SDOperand N0 = N.getOperand(0);\n"
1813 << " SDOperand N1 = N.getOperand(1);\n"
1814 << " SDOperand N2 = N.getOperand(2);\n"
1815 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1816 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1817 << " AddToISelQueue(N1);\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001818 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001819 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
Evan Cheng3393f892007-10-12 08:39:02 +00001820 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001821 << " N.getValueType(), Ops+1, 2);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001822 << " } else {\n"
1823 << " AddToISelQueue(N0);\n"
Evan Cheng3393f892007-10-12 08:39:02 +00001824 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner44f14762007-10-24 06:25:09 +00001825 << " N.getValueType(), Ops, 3);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001826 << " }\n"
1827 << "}\n\n";
1828
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001829 OS << "// The main instruction selector code.\n"
Evan Cheng9ade2182006-08-26 05:34:46 +00001830 << "SDNode *SelectCode(SDOperand N) {\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001831 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
Chris Lattnerb277cbc2005-10-18 04:41:01 +00001832 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
Evan Cheng34167212006-02-09 00:37:58 +00001833 << "INSTRUCTION_LIST_END)) {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001834 << " return NULL; // Already selected.\n"
Evan Cheng34167212006-02-09 00:37:58 +00001835 << " }\n\n"
Evan Cheng892aaf82006-11-08 23:01:03 +00001836 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
Chris Lattner547394c2005-09-23 21:53:45 +00001837 << " switch (N.getOpcode()) {\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001838 << " default: break;\n"
1839 << " case ISD::EntryToken: // These leaves remain the same.\n"
Chris Lattner5216c692005-12-18 21:05:44 +00001840 << " case ISD::BasicBlock:\n"
Chris Lattner8020a522006-01-11 19:52:27 +00001841 << " case ISD::Register:\n"
Evan Cheng0a83ed52006-02-05 08:46:14 +00001842 << " case ISD::HANDLENODE:\n"
Evan Cheng2216d8a2006-02-05 05:22:18 +00001843 << " case ISD::TargetConstant:\n"
1844 << " case ISD::TargetConstantPool:\n"
1845 << " case ISD::TargetFrameIndex:\n"
Chris Lattner4ef9b112007-05-15 01:36:44 +00001846 << " case ISD::TargetExternalSymbol:\n"
Nate Begeman37efe672006-04-22 18:53:45 +00001847 << " case ISD::TargetJumpTable:\n"
Lauro Ramos Venanciob3a04172007-04-20 21:38:10 +00001848 << " case ISD::TargetGlobalTLSAddress:\n"
Evan Cheng34167212006-02-09 00:37:58 +00001849 << " case ISD::TargetGlobalAddress: {\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001850 << " return NULL;\n"
Evan Cheng34167212006-02-09 00:37:58 +00001851 << " }\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001852 << " case ISD::AssertSext:\n"
Chris Lattnerfab37282005-09-26 22:10:24 +00001853 << " case ISD::AssertZext: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00001854 << " AddToISelQueue(N.getOperand(0));\n"
1855 << " ReplaceUses(N, N.getOperand(0));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001856 << " return NULL;\n"
Chris Lattnerf071bb52005-10-25 20:35:14 +00001857 << " }\n"
1858 << " case ISD::TokenFactor:\n"
Chris Lattner706d2d32006-08-09 16:44:44 +00001859 << " case ISD::CopyFromReg:\n"
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001860 << " case ISD::CopyToReg: {\n"
Evan Cheng676d7312006-08-26 00:59:04 +00001861 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1862 << " AddToISelQueue(N.getOperand(i));\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001863 << " return NULL;\n"
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001864 << " }\n"
Jim Laskeya683f9b2007-01-26 17:29:20 +00001865 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Christopher Lamb08d52072007-07-26 07:48:21 +00001866 << " case ISD::LABEL: return Select_LABEL(N);\n"
1867 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1868 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
Chris Lattnerfabcb7a2006-01-26 23:08:55 +00001869
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001870
Chris Lattner602f6922006-01-04 00:25:00 +00001871 // Loop over all of the case statements, emiting a call to each method we
1872 // emitted above.
Chris Lattner60d81392008-01-05 22:30:17 +00001873 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Evan Cheng892aaf82006-11-08 23:01:03 +00001874 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1875 PBOI != E; ++PBOI) {
1876 const std::string &OpName = PBOI->first;
Chris Lattner706d2d32006-08-09 16:44:44 +00001877 // Potentially multiple versions of select for this opcode. One for each
1878 // ValueType of the node (or its first true operand if it doesn't produce a
1879 // result.
1880 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1881 OpcodeVTMap.find(OpName);
1882 std::vector<std::string> &OpVTs = OpVTI->second;
Evan Cheng892aaf82006-11-08 23:01:03 +00001883 OS << " case " << OpName << ": {\n";
Evan Cheng425e8c72007-09-04 20:18:28 +00001884 // Keep track of whether we see a pattern that has an iPtr result.
1885 bool HasPtrPattern = false;
1886 bool HasDefaultPattern = false;
Chris Lattner717a6112006-11-14 21:50:27 +00001887
Evan Cheng425e8c72007-09-04 20:18:28 +00001888 OS << " switch (NVT) {\n";
1889 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1890 std::string &VTStr = OpVTs[i];
1891 if (VTStr.empty()) {
1892 HasDefaultPattern = true;
1893 continue;
1894 }
Chris Lattner717a6112006-11-14 21:50:27 +00001895
Evan Cheng425e8c72007-09-04 20:18:28 +00001896 // If this is a match on iPTR: don't emit it directly, we need special
1897 // code.
1898 if (VTStr == "_iPTR") {
1899 HasPtrPattern = true;
1900 continue;
Chris Lattner706d2d32006-08-09 16:44:44 +00001901 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001902 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1903 << " return Select_" << getLegalCName(OpName)
1904 << VTStr << "(N);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001905 }
Evan Cheng425e8c72007-09-04 20:18:28 +00001906 OS << " default:\n";
1907
1908 // If there is an iPTR result version of this pattern, emit it here.
1909 if (HasPtrPattern) {
1910 OS << " if (NVT == TLI.getPointerTy())\n";
1911 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1912 }
1913 if (HasDefaultPattern) {
1914 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1915 }
1916 OS << " break;\n";
1917 OS << " }\n";
1918 OS << " break;\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001919 OS << " }\n";
Chris Lattner81303322005-09-23 19:36:15 +00001920 }
Chris Lattner81303322005-09-23 19:36:15 +00001921
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001922 OS << " } // end of big switch.\n\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001923 << " cerr << \"Cannot yet select: \";\n"
Chris Lattnerb026e702006-03-28 00:41:33 +00001924 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1925 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1926 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00001927 << " N.Val->dump(CurDAG);\n"
1928 << " } else {\n"
1929 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1930 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001931 << " cerr << \"intrinsic %\"<< "
1932 "Intrinsic::getName((Intrinsic::ID)iid);\n"
Chris Lattner9bf2d3e2006-03-25 06:47:53 +00001933 << " }\n"
Bill Wendlingf5da1332006-12-07 22:21:48 +00001934 << " cerr << '\\n';\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001935 << " abort();\n"
Evan Cheng06d64702006-08-11 08:59:35 +00001936 << " return NULL;\n"
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001937 << "}\n";
1938}
1939
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001940void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner200c57e2008-01-05 22:58:54 +00001941 EmitSourceFileHeader("DAG Instruction Selector for the " +
1942 CGP.getTargetInfo().getName() + " target", OS);
Chris Lattner54cb8fd2005-09-07 23:44:43 +00001943
Chris Lattner1f39e292005-09-14 00:09:24 +00001944 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1945 << "// *** instruction selector class. These functions are really "
1946 << "methods.\n\n";
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00001947
Chris Lattner8dc728e2006-08-27 13:16:24 +00001948 OS << "#include \"llvm/Support/Compiler.h\"\n";
Evan Cheng233baf12006-07-26 23:06:27 +00001949
Chris Lattner706d2d32006-08-09 16:44:44 +00001950 OS << "// Instruction selector priority queue:\n"
1951 << "std::vector<SDNode*> ISelQueue;\n";
1952 OS << "/// Keep track of nodes which have already been added to queue.\n"
1953 << "unsigned char *ISelQueued;\n";
1954 OS << "/// Keep track of nodes which have already been selected.\n"
1955 << "unsigned char *ISelSelected;\n";
1956 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1957 << "std::vector<SDNode*> ISelKilled;\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00001958
Evan Cheng4326ef52006-10-12 02:08:53 +00001959 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1960 OS << "/// not reach Op.\n";
1961 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1962 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1963 OS << " return true;\n";
1964 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1965 OS << " return false;\n";
1966 OS << " else if (Chain->getNumOperands() > 0) {\n";
1967 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1968 OS << " if (C0.getValueType() == MVT::Other)\n";
1969 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1970 OS << " }\n";
1971 OS << " return true;\n";
1972 OS << "}\n";
1973
Chris Lattner706d2d32006-08-09 16:44:44 +00001974 OS << "/// Sorting functions for the selection queue.\n"
1975 << "struct isel_sort : public std::binary_function"
1976 << "<SDNode*, SDNode*, bool> {\n"
1977 << " bool operator()(const SDNode* left, const SDNode* right) "
1978 << "const {\n"
1979 << " return (left->getNodeId() > right->getNodeId());\n"
1980 << " }\n"
1981 << "};\n\n";
Evan Chenge41bf822006-02-05 06:43:12 +00001982
Chris Lattner706d2d32006-08-09 16:44:44 +00001983 OS << "inline void setQueued(int Id) {\n";
1984 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001985 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001986 OS << "inline bool isQueued(int Id) {\n";
1987 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001988 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001989 OS << "inline void setSelected(int Id) {\n";
1990 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00001991 OS << "}\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001992 OS << "inline bool isSelected(int Id) {\n";
1993 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
1994 OS << "}\n\n";
Evan Cheng9bdca032006-08-07 22:17:58 +00001995
Chris Lattner8dc728e2006-08-27 13:16:24 +00001996 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00001997 OS << " int Id = N.Val->getNodeId();\n";
1998 OS << " if (Id != -1 && !isQueued(Id)) {\n";
1999 OS << " ISelQueue.push_back(N.Val);\n";
2000 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2001 OS << " setQueued(Id);\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00002002 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002003 OS << "}\n\n";
Tanya Lattner8d4ccf02006-08-09 16:41:21 +00002004
Chris Lattner706d2d32006-08-09 16:44:44 +00002005 OS << "inline void RemoveKilled() {\n";
2006OS << " unsigned NumKilled = ISelKilled.size();\n";
2007 OS << " if (NumKilled) {\n";
2008 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
2009 OS << " SDNode *Temp = ISelKilled[i];\n";
Evan Cheng4f776162006-10-12 23:18:52 +00002010 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
2011 << "Temp), ISelQueue.end());\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002012 OS << " };\n";
2013 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2014 OS << " ISelKilled.clear();\n";
2015 OS << " }\n";
2016 OS << "}\n\n";
2017
Chris Lattner8dc728e2006-08-27 13:16:24 +00002018 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner01d029b2007-10-15 06:10:22 +00002019 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002020 OS << " setSelected(F.Val->getNodeId());\n";
2021 OS << " RemoveKilled();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002022 OS << "}\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002023 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
Evan Cheng30729b42007-09-17 22:26:41 +00002024 OS << " unsigned FNumVals = F->getNumValues();\n";
2025 OS << " unsigned TNumVals = T->getNumValues();\n";
2026 OS << " if (FNumVals != TNumVals) {\n";
2027 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2028 << "i < e; ++i)\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002029 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
Chris Lattner01d029b2007-10-15 06:10:22 +00002030 << "SDOperand(T, i), &ISelKilled);\n";
Evan Cheng85dbe1a2007-09-12 23:30:14 +00002031 OS << " } else {\n";
2032 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2033 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002034 OS << " setSelected(F->getNodeId());\n";
2035 OS << " RemoveKilled();\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002036 OS << "}\n\n";
2037
Evan Chenge41bf822006-02-05 06:43:12 +00002038 OS << "// SelectRoot - Top level entry to DAG isel.\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002039 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2040 OS << " SelectRootInit();\n";
2041 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2042 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2043 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2044 OS << " memset(ISelQueued, 0, NumBytes);\n";
2045 OS << " memset(ISelSelected, 0, NumBytes);\n";
2046 OS << "\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00002047 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2048 << " // a reference to the root node, preventing it from being deleted,\n"
2049 << " // and tracking any changes of the root.\n"
2050 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2051 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002052 OS << " while (!ISelQueue.empty()) {\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002053 OS << " SDNode *Node = ISelQueue.front();\n";
2054 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2055 OS << " ISelQueue.pop_back();\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002056 OS << " if (!isSelected(Node->getNodeId())) {\n";
Evan Cheng9ade2182006-08-26 05:34:46 +00002057 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
Evan Cheng966fd372006-09-11 02:24:43 +00002058 OS << " if (ResNode != Node) {\n";
2059 OS << " if (ResNode)\n";
2060 OS << " ReplaceUses(Node, ResNode);\n";
Evan Cheng1fae00f2006-10-12 20:35:19 +00002061 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2062 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2063 OS << " RemoveKilled();\n";
2064 OS << " }\n";
Evan Cheng966fd372006-09-11 02:24:43 +00002065 OS << " }\n";
Evan Cheng06d64702006-08-11 08:59:35 +00002066 OS << " }\n";
Chris Lattner706d2d32006-08-09 16:44:44 +00002067 OS << " }\n";
2068 OS << "\n";
2069 OS << " delete[] ISelQueued;\n";
2070 OS << " ISelQueued = NULL;\n";
2071 OS << " delete[] ISelSelected;\n";
2072 OS << " ISelSelected = NULL;\n";
Chris Lattnerdfb86072006-08-15 23:42:26 +00002073 OS << " return Dummy.getValue();\n";
Evan Chenge41bf822006-02-05 06:43:12 +00002074 OS << "}\n";
Chris Lattner296dfe32005-09-24 00:50:51 +00002075
Chris Lattner443e3f92008-01-05 22:54:53 +00002076 EmitNodeTransforms(OS);
Chris Lattnerdc32f982008-01-05 22:43:57 +00002077 EmitPredicateFunctions(OS);
2078
Bill Wendlingf5da1332006-12-07 22:21:48 +00002079 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerfe718932008-01-06 01:10:31 +00002080 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner6cefb772008-01-05 22:25:12 +00002081 I != E; ++I) {
2082 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2083 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Bill Wendlingf5da1332006-12-07 22:21:48 +00002084 DOUT << "\n";
2085 }
Chris Lattnere46e17b2005-09-29 19:28:10 +00002086
Chris Lattnerb9f01eb2005-09-16 00:29:46 +00002087 // At this point, we have full information about the 'Patterns' we need to
2088 // parse, both implicitly from instructions as well as from explicit pattern
Chris Lattnere97603f2005-09-28 19:27:25 +00002089 // definitions. Emit the resultant instruction selector.
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002090 EmitInstructionSelector(OS);
2091
Chris Lattner54cb8fd2005-09-07 23:44:43 +00002092}