blob: 14b261a1d482cfad4c134ffbcbb7794daf957df6 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- DAGISelEmitter.cpp - Generate an instruction selector --------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattnerfd6c2f02007-12-29 20:37:13 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This tablegen backend emits a DAG instruction selector.
11//
12//===----------------------------------------------------------------------===//
13
14#include "DAGISelEmitter.h"
15#include "Record.h"
16#include "llvm/ADT/StringExtras.h"
David Greene932618b2008-10-27 21:56:29 +000017#include "llvm/Support/CommandLine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000018#include "llvm/Support/Debug.h"
19#include "llvm/Support/MathExtras.h"
David Greene932618b2008-10-27 21:56:29 +000020#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021#include "llvm/Support/Streams.h"
22#include <algorithm>
Dan Gohman6761ff52008-07-07 21:00:17 +000023#include <deque>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000024using namespace llvm;
25
David Greene932618b2008-10-27 21:56:29 +000026namespace {
27 cl::opt<bool>
28 GenDebug("gen-debug", cl::desc("Generate debug code"),
29 cl::init(false));
30}
31
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +000033// DAGISelEmitter Helper methods
Dan Gohmanf17a25c2007-07-18 16:29:46 +000034//
35
Chris Lattner4ca8ff02008-01-05 22:25:12 +000036/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
37/// ComplexPattern.
38static bool NodeIsComplexPattern(TreePatternNode *N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000039 return (N->isLeaf() &&
40 dynamic_cast<DefInit*>(N->getLeafValue()) &&
41 static_cast<DefInit*>(N->getLeafValue())->getDef()->
42 isSubClassOf("ComplexPattern"));
43}
44
Chris Lattner4ca8ff02008-01-05 22:25:12 +000045/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
46/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000047static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerae506702008-01-06 01:10:31 +000048 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049 if (N->isLeaf() &&
50 dynamic_cast<DefInit*>(N->getLeafValue()) &&
51 static_cast<DefInit*>(N->getLeafValue())->getDef()->
52 isSubClassOf("ComplexPattern")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +000053 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
54 ->getDef());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000055 }
56 return NULL;
57}
58
59/// getPatternSize - Return the 'size' of this pattern. We want to match large
60/// patterns before small ones. This is used to determine the size of a
61/// pattern.
Chris Lattnerae506702008-01-06 01:10:31 +000062static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Duncan Sands92c43912008-06-06 12:08:01 +000063 assert((EMVT::isExtIntegerInVTs(P->getExtTypes()) ||
64 EMVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000065 P->getExtTypeNum(0) == MVT::isVoid ||
66 P->getExtTypeNum(0) == MVT::Flag ||
Mon P Wangce3ac892008-07-30 04:36:53 +000067 P->getExtTypeNum(0) == MVT::iPTR ||
68 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000069 "Not a valid pattern node to size!");
70 unsigned Size = 3; // The node itself.
71 // If the root node is a ConstantSDNode, increases its size.
72 // e.g. (set R32:$dst, 0).
73 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
74 Size += 2;
75
76 // FIXME: This is a hack to statically increase the priority of patterns
77 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
78 // Later we can allow complexity / cost for each pattern to be (optionally)
79 // specified. To get best possible pattern match we'll need to dynamically
80 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner4ca8ff02008-01-05 22:25:12 +000081 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000082 if (AM)
83 Size += AM->getNumOperands() * 3;
84
85 // If this node has some predicate function that must match, it adds to the
86 // complexity of this node.
Dan Gohman5394e112008-10-15 06:17:21 +000087 if (!P->getPredicateFns().empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 ++Size;
89
90 // Count children in the count if they are also nodes.
91 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
92 TreePatternNode *Child = P->getChild(i);
93 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner4ca8ff02008-01-05 22:25:12 +000094 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000095 else if (Child->isLeaf()) {
96 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
97 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
98 else if (NodeIsComplexPattern(Child))
Chris Lattner4ca8ff02008-01-05 22:25:12 +000099 Size += getPatternSize(Child, CGP);
Dan Gohman5394e112008-10-15 06:17:21 +0000100 else if (!Child->getPredicateFns().empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 ++Size;
102 }
103 }
104
105 return Size;
106}
107
108/// getResultPatternCost - Compute the number of instructions for this pattern.
109/// This is a temporary hack. We should really include the instruction
110/// latencies in this calculation.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000111static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000112 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000113 if (P->isLeaf()) return 0;
114
115 unsigned Cost = 0;
116 Record *Op = P->getOperator();
117 if (Op->isSubClassOf("Instruction")) {
118 Cost++;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000119 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120 if (II.usesCustomDAGSchedInserter)
121 Cost += 10;
122 }
123 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000124 Cost += getResultPatternCost(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000125 return Cost;
126}
127
128/// getResultPatternCodeSize - Compute the code size of instructions for this
129/// pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000130static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000131 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132 if (P->isLeaf()) return 0;
133
134 unsigned Cost = 0;
135 Record *Op = P->getOperator();
136 if (Op->isSubClassOf("Instruction")) {
137 Cost += Op->getValueAsInt("CodeSize");
138 }
139 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000140 Cost += getResultPatternSize(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 return Cost;
142}
143
144// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
145// In particular, we want to match maximal patterns first and lowest cost within
146// a particular complexity first.
147struct PatternSortingPredicate {
Chris Lattnerae506702008-01-06 01:10:31 +0000148 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
149 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150
Dan Gohman5394e112008-10-15 06:17:21 +0000151 typedef std::pair<unsigned, std::string> CodeLine;
152 typedef std::vector<CodeLine> CodeList;
153 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
154
155 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
156 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
157 const PatternToMatch *LHS = LHSPair.first;
158 const PatternToMatch *RHS = RHSPair.first;
159
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000160 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
161 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000162 LHSSize += LHS->getAddedComplexity();
163 RHSSize += RHS->getAddedComplexity();
164 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
165 if (LHSSize < RHSSize) return false;
166
167 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000168 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
169 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000170 if (LHSCost < RHSCost) return true;
171 if (LHSCost > RHSCost) return false;
172
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000173 return getResultPatternSize(LHS->getDstPattern(), CGP) <
174 getResultPatternSize(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 }
176};
177
178/// getRegisterValueType - Look up and return the first ValueType of specified
179/// RegisterClass record
Duncan Sands92c43912008-06-06 12:08:01 +0000180static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000181 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
182 return RC->getValueTypeNum(0);
183 return MVT::Other;
184}
185
186
187/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
188/// type information from it.
189static void RemoveAllTypes(TreePatternNode *N) {
190 N->removeTypes();
191 if (!N->isLeaf())
192 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
193 RemoveAllTypes(N->getChild(i));
194}
195
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196/// NodeHasProperty - return true if TreePatternNode has the specified
197/// property.
198static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000199 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000200 if (N->isLeaf()) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000201 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000202 if (CP)
203 return CP->hasProperty(Property);
204 return false;
205 }
206 Record *Operator = N->getOperator();
207 if (!Operator->isSubClassOf("SDNode")) return false;
208
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000209 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210}
211
212static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000213 CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000214 if (NodeHasProperty(N, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 return true;
216
217 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
218 TreePatternNode *Child = N->getChild(i);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000219 if (PatternHasProperty(Child, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 return true;
221 }
222
223 return false;
224}
225
Evan Cheng43f0c652008-07-03 08:39:51 +0000226static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
227 return CGP.getSDNodeInfo(Op).getEnumName();
228}
229
230static
231bool DisablePatternForFastISel(TreePatternNode *N, CodeGenDAGPatterns &CGP) {
232 bool isStore = !N->isLeaf() &&
233 getOpcodeName(N->getOperator(), CGP) == "ISD::STORE";
234 if (!isStore && NodeHasProperty(N, SDNPHasChain, CGP))
235 return false;
236
237 bool HasChain = false;
238 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
239 TreePatternNode *Child = N->getChild(i);
240 if (PatternHasProperty(Child, SDNPHasChain, CGP)) {
241 HasChain = true;
242 break;
243 }
244 }
245 return HasChain;
246}
247
Chris Lattner7fdd9342008-01-05 22:43:57 +0000248//===----------------------------------------------------------------------===//
Chris Lattner227da452008-01-05 22:54:53 +0000249// Node Transformation emitter implementation.
250//
251void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
252 // Walk the pattern fragments, adding them to a map, which sorts them by
253 // name.
Chris Lattnerae506702008-01-06 01:10:31 +0000254 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner227da452008-01-05 22:54:53 +0000255 NXsByNameTy NXsByName;
256
Chris Lattnerae506702008-01-06 01:10:31 +0000257 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner227da452008-01-05 22:54:53 +0000258 I != E; ++I)
259 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
260
261 OS << "\n// Node transformations.\n";
262
263 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
264 I != E; ++I) {
265 Record *SDNode = I->second.first;
266 std::string Code = I->second.second;
267
268 if (Code.empty()) continue; // Empty code? Skip it.
269
Chris Lattner14948ea2008-01-05 22:58:54 +0000270 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner227da452008-01-05 22:54:53 +0000271 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
272
Dan Gohman8181bd12008-07-27 21:46:04 +0000273 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner227da452008-01-05 22:54:53 +0000274 << ") {\n";
275 if (ClassName != "SDNode")
276 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
277 OS << Code << "\n}\n";
278 }
279}
280
281//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +0000282// Predicate emitter implementation.
283//
284
285void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
286 OS << "\n// Predicate functions.\n";
287
288 // Walk the pattern fragments, adding them to a map, which sorts them by
289 // name.
290 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
291 PFsByNameTy PFsByName;
292
Chris Lattnerae506702008-01-06 01:10:31 +0000293 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000294 I != E; ++I)
295 PFsByName.insert(std::make_pair(I->first->getName(), *I));
296
297
298 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
299 I != E; ++I) {
300 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
301 TreePattern *P = I->second.second;
302
303 // If there is a code init for this fragment, emit the predicate code.
304 std::string Code = PatFragRecord->getValueAsCode("Predicate");
305 if (Code.empty()) continue;
306
307 if (P->getOnlyTree()->isLeaf())
308 OS << "inline bool Predicate_" << PatFragRecord->getName()
309 << "(SDNode *N) {\n";
310 else {
311 std::string ClassName =
Chris Lattner14948ea2008-01-05 22:58:54 +0000312 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000313 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
314
315 OS << "inline bool Predicate_" << PatFragRecord->getName()
316 << "(SDNode *" << C2 << ") {\n";
317 if (ClassName != "SDNode")
318 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
319 }
320 OS << Code << "\n}\n";
321 }
322
323 OS << "\n\n";
324}
325
326
327//===----------------------------------------------------------------------===//
328// PatternCodeEmitter implementation.
329//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000330class PatternCodeEmitter {
331private:
Chris Lattnerae506702008-01-06 01:10:31 +0000332 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000333
334 // Predicates.
Dan Gohmane97f1a32008-08-22 00:20:26 +0000335 std::string PredicateCheck;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336 // Pattern cost.
337 unsigned Cost;
338 // Instruction selector pattern.
339 TreePatternNode *Pattern;
340 // Matched instruction.
341 TreePatternNode *Instruction;
342
343 // Node to name mapping
344 std::map<std::string, std::string> VariableMap;
345 // Node to operator mapping
346 std::map<std::string, Record*> OperatorMap;
Evan Cheng07f307d2008-02-05 22:50:29 +0000347 // Name of the folded node which produces a flag.
348 std::pair<std::string, unsigned> FoldedFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 // Names of all the folded nodes which produce chains.
350 std::vector<std::pair<std::string, unsigned> > FoldedChains;
351 // Original input chain(s).
352 std::vector<std::pair<std::string, std::string> > OrigChains;
353 std::set<std::string> Duplicates;
354
Dan Gohman12a9c082008-02-06 22:27:42 +0000355 /// LSI - Load/Store information.
356 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
357 /// for each memory access. This facilitates the use of AliasAnalysis in
358 /// the backend.
359 std::vector<std::string> LSI;
360
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000361 /// GeneratedCode - This is the buffer that we emit code to. The first int
362 /// indicates whether this is an exit predicate (something that should be
363 /// tested, and if true, the match fails) [when 1], or normal code to emit
364 /// [when 0], or initialization code to emit [when 2].
365 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman8181bd12008-07-27 21:46:04 +0000366 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367 /// the set of patterns for each top-level opcode.
368 std::set<std::string> &GeneratedDecl;
369 /// TargetOpcodes - The target specific opcodes used by the resulting
370 /// instructions.
371 std::vector<std::string> &TargetOpcodes;
372 std::vector<std::string> &TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000373 /// OutputIsVariadic - Records whether the instruction output pattern uses
374 /// variable_ops. This requires that the Emit function be passed an
375 /// additional argument to indicate where the input varargs operands
376 /// begin.
377 bool &OutputIsVariadic;
378 /// NumInputRootOps - Records the number of operands the root node of the
379 /// input pattern has. This information is used in the generated code to
380 /// pass to Emit functions when variable_ops processing is needed.
381 unsigned &NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000382
383 std::string ChainName;
384 unsigned TmpNo;
385 unsigned OpcNo;
386 unsigned VTNo;
387
388 void emitCheck(const std::string &S) {
389 if (!S.empty())
390 GeneratedCode.push_back(std::make_pair(1, S));
391 }
392 void emitCode(const std::string &S) {
393 if (!S.empty())
394 GeneratedCode.push_back(std::make_pair(0, S));
395 }
396 void emitInit(const std::string &S) {
397 if (!S.empty())
398 GeneratedCode.push_back(std::make_pair(2, S));
399 }
400 void emitDecl(const std::string &S) {
401 assert(!S.empty() && "Invalid declaration");
402 GeneratedDecl.insert(S);
403 }
404 void emitOpcode(const std::string &Opc) {
405 TargetOpcodes.push_back(Opc);
406 OpcNo++;
407 }
408 void emitVT(const std::string &VT) {
409 TargetVTs.push_back(VT);
410 VTNo++;
411 }
412public:
Dan Gohmane97f1a32008-08-22 00:20:26 +0000413 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 TreePatternNode *pattern, TreePatternNode *instr,
415 std::vector<std::pair<unsigned, std::string> > &gc,
416 std::set<std::string> &gd,
417 std::vector<std::string> &to,
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000418 std::vector<std::string> &tv,
419 bool &oiv,
420 unsigned &niro)
Dan Gohmane97f1a32008-08-22 00:20:26 +0000421 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 GeneratedCode(gc), GeneratedDecl(gd),
423 TargetOpcodes(to), TargetVTs(tv),
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000424 OutputIsVariadic(oiv), NumInputRootOps(niro),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000425 TmpNo(0), OpcNo(0), VTNo(0) {}
426
427 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
428 /// if the match fails. At this point, we already know that the opcode for N
429 /// matches, and the SDNode for the result has the RootName specified name.
430 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
431 const std::string &RootName, const std::string &ChainSuffix,
432 bool &FoundChain) {
Dan Gohman12a9c082008-02-06 22:27:42 +0000433
434 // Save loads/stores matched by a pattern.
435 if (!N->isLeaf() && N->getName().empty()) {
Mon P Wang6bde9ec2008-06-25 08:15:39 +0000436 if (NodeHasProperty(N, SDNPMemOperand, CGP))
Dan Gohman12a9c082008-02-06 22:27:42 +0000437 LSI.push_back(RootName);
Dan Gohman12a9c082008-02-06 22:27:42 +0000438 }
439
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000440 bool isRoot = (P == NULL);
441 // Emit instruction predicates. Each predicate is just a string for now.
442 if (isRoot) {
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000443 // Record input varargs info.
444 NumInputRootOps = N->getNumChildren();
445
Evan Cheng43f0c652008-07-03 08:39:51 +0000446 if (DisablePatternForFastISel(N, CGP))
Dan Gohmana29efcf2008-08-13 19:55:00 +0000447 emitCheck("!Fast");
Evan Cheng43f0c652008-07-03 08:39:51 +0000448
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000449 emitCheck(PredicateCheck);
450 }
451
452 if (N->isLeaf()) {
453 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
454 emitCheck("cast<ConstantSDNode>(" + RootName +
Dan Gohman9a18b792008-10-17 04:40:39 +0000455 ")->getSExtValue() == INT64_C(" +
456 itostr(II->getValue()) + ")");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000457 return;
458 } else if (!NodeIsComplexPattern(N)) {
459 assert(0 && "Cannot match this as a leaf value!");
460 abort();
461 }
462 }
463
464 // If this node has a name associated with it, capture it in VariableMap. If
465 // we already saw this in the pattern, emit code to verify dagness.
466 if (!N->getName().empty()) {
467 std::string &VarMapEntry = VariableMap[N->getName()];
468 if (VarMapEntry.empty()) {
469 VarMapEntry = RootName;
470 } else {
471 // If we get here, this is a second reference to a specific name. Since
472 // we already have checked that the first reference is valid, we don't
473 // have to recursively match it, just check that it's the same as the
474 // previously named thing.
475 emitCheck(VarMapEntry + " == " + RootName);
476 return;
477 }
478
479 if (!N->isLeaf())
480 OperatorMap[N->getName()] = N->getOperator();
481 }
482
483
484 // Emit code to load the child nodes and match their contents recursively.
485 unsigned OpNo = 0;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000486 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
487 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488 bool EmittedUseCheck = false;
489 if (HasChain) {
490 if (NodeHasChain)
491 OpNo = 1;
492 if (!isRoot) {
493 // Multiple uses of actual result?
494 emitCheck(RootName + ".hasOneUse()");
495 EmittedUseCheck = true;
496 if (NodeHasChain) {
497 // If the immediate use can somehow reach this node through another
498 // path, then can't fold it either or it will create a cycle.
499 // e.g. In the following diagram, XX can reach ld through YY. If
500 // ld is folded into XX, then YY is both a predecessor and a successor
501 // of XX.
502 //
503 // [ld]
504 // ^ ^
505 // | |
506 // / \---
507 // / [YY]
508 // | ^
509 // [XX]-------|
Evan Cheng43f0c652008-07-03 08:39:51 +0000510 bool NeedCheck = P != Pattern;
511 if (!NeedCheck) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000512 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000513 NeedCheck =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000514 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
515 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
516 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 PInfo.getNumOperands() > 1 ||
518 PInfo.hasProperty(SDNPHasChain) ||
519 PInfo.hasProperty(SDNPInFlag) ||
520 PInfo.hasProperty(SDNPOptInFlag);
521 }
522
523 if (NeedCheck) {
524 std::string ParentName(RootName.begin(), RootName.end()-1);
Evan Cheng5a424552008-11-27 00:49:46 +0000525 emitCheck("IsLegalAndProfitableToFold(" + RootName +
526 ".getNode(), " + ParentName + ".getNode(), N.getNode())");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000527 }
528 }
529 }
530
531 if (NodeHasChain) {
532 if (FoundChain) {
Gabor Greif1c80d112008-08-28 21:40:38 +0000533 emitCheck("(" + ChainName + ".getNode() == " + RootName + ".getNode() || "
534 "IsChainCompatible(" + ChainName + ".getNode(), " +
535 RootName + ".getNode()))");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000536 OrigChains.push_back(std::make_pair(ChainName, RootName));
537 } else
538 FoundChain = true;
539 ChainName = "Chain" + ChainSuffix;
Dan Gohman8181bd12008-07-27 21:46:04 +0000540 emitInit("SDValue " + ChainName + " = " + RootName +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000541 ".getOperand(0);");
542 }
543 }
544
545 // Don't fold any node which reads or writes a flag and has multiple uses.
546 // FIXME: We really need to separate the concepts of flag and "glue". Those
547 // real flag results, e.g. X86CMP output, can have multiple uses.
548 // FIXME: If the optional incoming flag does not exist. Then it is ok to
549 // fold it.
550 if (!isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000551 (PatternHasProperty(N, SDNPInFlag, CGP) ||
552 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
553 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 if (!EmittedUseCheck) {
555 // Multiple uses of actual result?
556 emitCheck(RootName + ".hasOneUse()");
557 }
558 }
559
Dan Gohman5394e112008-10-15 06:17:21 +0000560 // If there are node predicates for this, emit the calls.
561 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
562 emitCheck(N->getPredicateFns()[i] + "(" + RootName + ".getNode())");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000563
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000564 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
565 // a constant without a predicate fn that has more that one bit set, handle
566 // this as a special case. This is usually for targets that have special
567 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
568 // handling stuff). Using these instructions is often far more efficient
569 // than materializing the constant. Unfortunately, both the instcombiner
570 // and the dag combiner can often infer that bits are dead, and thus drop
571 // them from the mask in the dag. For example, it might turn 'AND X, 255'
572 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
573 // to handle this.
574 if (!N->isLeaf() &&
575 (N->getOperator()->getName() == "and" ||
576 N->getOperator()->getName() == "or") &&
577 N->getChild(1)->isLeaf() &&
Dan Gohman5394e112008-10-15 06:17:21 +0000578 N->getChild(1)->getPredicateFns().empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000579 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
580 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
Dan Gohman8181bd12008-07-27 21:46:04 +0000581 emitInit("SDValue " + RootName + "0" + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 RootName + ".getOperand(" + utostr(0) + ");");
Dan Gohman8181bd12008-07-27 21:46:04 +0000583 emitInit("SDValue " + RootName + "1" + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 RootName + ".getOperand(" + utostr(1) + ");");
585
Dan Gohman1cbafa12008-12-19 18:13:39 +0000586 unsigned NTmp = TmpNo++;
587 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
588 " = dyn_cast<ConstantSDNode>(" + RootName + "1);");
589 emitCheck("Tmp" + utostr(NTmp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000590 const char *MaskPredicate = N->getOperator()->getName() == "or"
591 ? "CheckOrMask(" : "CheckAndMask(";
Dan Gohman1cbafa12008-12-19 18:13:39 +0000592 emitCheck(MaskPredicate + RootName + "0, Tmp" + utostr(NTmp) +
593 ", INT64_C(" + itostr(II->getValue()) + "))");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000594
Christopher Lamb059c7c92008-01-31 07:27:46 +0000595 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000596 ChainSuffix + utostr(0), FoundChain);
597 return;
598 }
599 }
600 }
601
602 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000603 emitInit("SDValue " + RootName + utostr(OpNo) + " = " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000604 RootName + ".getOperand(" +utostr(OpNo) + ");");
605
Christopher Lamb059c7c92008-01-31 07:27:46 +0000606 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 ChainSuffix + utostr(OpNo), FoundChain);
608 }
609
610 // Handle cases when root is a complex pattern.
611 const ComplexPattern *CP;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000612 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 std::string Fn = CP->getSelectFunc();
614 unsigned NumOps = CP->getNumOperands();
615 for (unsigned i = 0; i < NumOps; ++i) {
Dan Gohmanba5cbd92009-01-16 02:05:52 +0000616 emitDecl("CPTmp" + RootName + "_" + utostr(i));
617 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000618 }
619 if (CP->hasProperty(SDNPHasChain)) {
620 emitDecl("CPInChain");
621 emitDecl("Chain" + ChainSuffix);
Dan Gohman8181bd12008-07-27 21:46:04 +0000622 emitCode("SDValue CPInChain;");
623 emitCode("SDValue Chain" + ChainSuffix + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624 }
625
626 std::string Code = Fn + "(" + RootName + ", " + RootName;
627 for (unsigned i = 0; i < NumOps; i++)
Dan Gohmanba5cbd92009-01-16 02:05:52 +0000628 Code += ", CPTmp" + RootName + "_" + utostr(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000629 if (CP->hasProperty(SDNPHasChain)) {
630 ChainName = "Chain" + ChainSuffix;
631 Code += ", CPInChain, Chain" + ChainSuffix;
632 }
633 emitCheck(Code + ")");
634 }
635 }
636
637 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb059c7c92008-01-31 07:27:46 +0000638 const std::string &RootName,
639 const std::string &ParentRootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000640 const std::string &ChainSuffix, bool &FoundChain) {
641 if (!Child->isLeaf()) {
642 // If it's not a leaf, recursively match.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000643 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 emitCheck(RootName + ".getOpcode() == " +
645 CInfo.getEnumName());
646 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Evan Cheng07f307d2008-02-05 22:50:29 +0000647 bool HasChain = false;
648 if (NodeHasProperty(Child, SDNPHasChain, CGP)) {
649 HasChain = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000650 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
Evan Cheng07f307d2008-02-05 22:50:29 +0000651 }
652 if (NodeHasProperty(Child, SDNPOutFlag, CGP)) {
653 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
654 "Pattern folded multiple nodes which produce flags?");
655 FoldedFlag = std::make_pair(RootName,
656 CInfo.getNumResults() + (unsigned)HasChain);
657 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000658 } else {
659 // If this child has a name associated with it, capture it in VarMap. If
660 // we already saw this in the pattern, emit code to verify dagness.
661 if (!Child->getName().empty()) {
662 std::string &VarMapEntry = VariableMap[Child->getName()];
663 if (VarMapEntry.empty()) {
664 VarMapEntry = RootName;
665 } else {
666 // If we get here, this is a second reference to a specific name.
667 // Since we already have checked that the first reference is valid,
668 // we don't have to recursively match it, just check that it's the
669 // same as the previously named thing.
670 emitCheck(VarMapEntry + " == " + RootName);
671 Duplicates.insert(RootName);
672 return;
673 }
674 }
675
676 // Handle leaves of various types.
677 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
678 Record *LeafRec = DI->getDef();
679 if (LeafRec->isSubClassOf("RegisterClass") ||
680 LeafRec->getName() == "ptr_rc") {
681 // Handle register references. Nothing to do here.
682 } else if (LeafRec->isSubClassOf("Register")) {
683 // Handle register references.
684 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
685 // Handle complex pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000686 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000687 std::string Fn = CP->getSelectFunc();
688 unsigned NumOps = CP->getNumOperands();
689 for (unsigned i = 0; i < NumOps; ++i) {
Dan Gohmanba5cbd92009-01-16 02:05:52 +0000690 emitDecl("CPTmp" + RootName + "_" + utostr(i));
691 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000692 }
693 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000694 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 FoldedChains.push_back(std::make_pair("CPInChain",
696 PInfo.getNumResults()));
697 ChainName = "Chain" + ChainSuffix;
698 emitDecl("CPInChain");
699 emitDecl(ChainName);
Dan Gohman8181bd12008-07-27 21:46:04 +0000700 emitCode("SDValue CPInChain;");
701 emitCode("SDValue " + ChainName + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 }
703
Christopher Lamb059c7c92008-01-31 07:27:46 +0000704 std::string Code = Fn + "(";
705 if (CP->hasAttribute(CPAttrParentAsRoot)) {
706 Code += ParentRootName + ", ";
707 } else {
708 Code += "N, ";
709 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000710 if (CP->hasProperty(SDNPHasChain)) {
711 std::string ParentName(RootName.begin(), RootName.end()-1);
712 Code += ParentName + ", ";
713 }
714 Code += RootName;
715 for (unsigned i = 0; i < NumOps; i++)
Dan Gohmanba5cbd92009-01-16 02:05:52 +0000716 Code += ", CPTmp" + RootName + "_" + utostr(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 if (CP->hasProperty(SDNPHasChain))
718 Code += ", CPInChain, Chain" + ChainSuffix;
719 emitCheck(Code + ")");
720 } else if (LeafRec->getName() == "srcvalue") {
721 // Place holder for SRCVALUE nodes. Nothing to do here.
722 } else if (LeafRec->isSubClassOf("ValueType")) {
723 // Make sure this is the specified value type.
724 emitCheck("cast<VTSDNode>(" + RootName +
725 ")->getVT() == MVT::" + LeafRec->getName());
726 } else if (LeafRec->isSubClassOf("CondCode")) {
727 // Make sure this is the specified cond code.
728 emitCheck("cast<CondCodeSDNode>(" + RootName +
729 ")->get() == ISD::" + LeafRec->getName());
730 } else {
731#ifndef NDEBUG
732 Child->dump();
733 cerr << " ";
734#endif
735 assert(0 && "Unknown leaf type!");
736 }
737
Dan Gohman5394e112008-10-15 06:17:21 +0000738 // If there are node predicates for this, emit the calls.
739 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
740 emitCheck(Child->getPredicateFns()[i] + "(" + RootName +
Gabor Greif1c80d112008-08-28 21:40:38 +0000741 ".getNode())");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000742 } else if (IntInit *II =
743 dynamic_cast<IntInit*>(Child->getLeafValue())) {
Dan Gohman1cbafa12008-12-19 18:13:39 +0000744 unsigned NTmp = TmpNo++;
745 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
746 " = dyn_cast<ConstantSDNode>("+
747 RootName + ");");
748 emitCheck("Tmp" + utostr(NTmp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000749 unsigned CTmp = TmpNo++;
Dan Gohman1cbafa12008-12-19 18:13:39 +0000750 emitCode("int64_t CN"+ utostr(CTmp) +
751 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
Dan Gohman5a5e6e92008-10-17 01:33:43 +0000752 emitCheck("CN" + utostr(CTmp) + " == "
753 "INT64_C(" +itostr(II->getValue()) + ")");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 } else {
755#ifndef NDEBUG
756 Child->dump();
757#endif
758 assert(0 && "Unknown leaf type!");
759 }
760 }
761 }
762
763 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
764 /// we actually have to build a DAG!
765 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000766 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000767 bool InFlagDecled, bool ResNodeDecled,
768 bool LikeLeaf = false, bool isRoot = false) {
769 // List of arguments of getTargetNode() or SelectNodeTo().
770 std::vector<std::string> NodeOps;
771 // This is something selected from the pattern we matched.
772 if (!N->getName().empty()) {
Scott Michel30124c22008-01-29 02:29:31 +0000773 const std::string &VarName = N->getName();
774 std::string Val = VariableMap[VarName];
775 bool ModifiedVal = false;
Scott Michelac7091c2008-02-15 23:05:48 +0000776 if (Val.empty()) {
Bill Wendling39d33752008-02-26 10:45:29 +0000777 cerr << "Variable '" << VarName << " referenced but not defined "
778 << "and not caught earlier!\n";
779 abort();
Scott Michelac7091c2008-02-15 23:05:48 +0000780 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
782 // Already selected this operand, just return the tmpval.
783 NodeOps.push_back(Val);
784 return NodeOps;
785 }
786
787 const ComplexPattern *CP;
788 unsigned ResNo = TmpNo++;
789 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
790 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
791 std::string CastType;
Scott Michel30124c22008-01-29 02:29:31 +0000792 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000793 switch (N->getTypeNum(0)) {
794 default:
795 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
796 << " type as an immediate constant. Aborting\n";
797 abort();
798 case MVT::i1: CastType = "bool"; break;
799 case MVT::i8: CastType = "unsigned char"; break;
800 case MVT::i16: CastType = "unsigned short"; break;
801 case MVT::i32: CastType = "unsigned"; break;
802 case MVT::i64: CastType = "uint64_t"; break;
803 }
Dan Gohman8181bd12008-07-27 21:46:04 +0000804 emitCode("SDValue " + TmpVar +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000805 " = CurDAG->getTargetConstant(((" + CastType +
Dan Gohmanfaeb4a32008-09-12 16:56:44 +0000806 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000807 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
809 // value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000810 Val = TmpVar;
811 ModifiedVal = true;
812 NodeOps.push_back(Val);
Nate Begemane2ba64f2008-02-14 08:57:00 +0000813 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
814 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
815 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000816 emitCode("SDValue " + TmpVar +
Dan Gohmanc1f3a072008-09-12 18:08:03 +0000817 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
818 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
819 Val + ")->getValueType(0));");
Nate Begemane2ba64f2008-02-14 08:57:00 +0000820 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
821 // value if used multiple times by this pattern result.
822 Val = TmpVar;
823 ModifiedVal = true;
824 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
826 Record *Op = OperatorMap[N->getName()];
Bill Wendlingfef06052008-09-16 21:48:12 +0000827 // Transform ExternalSymbol to TargetExternalSymbol
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000828 if (Op && Op->getName() == "externalsym") {
Scott Michel30124c22008-01-29 02:29:31 +0000829 std::string TmpVar = "Tmp"+utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000830 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
Bill Wendlingfef06052008-09-16 21:48:12 +0000831 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 Val + ")->getSymbol(), " +
833 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000834 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
835 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000836 Val = TmpVar;
837 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000838 }
Scott Michel30124c22008-01-29 02:29:31 +0000839 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000840 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
841 || N->getOperator()->getName() == "tglobaltlsaddr")) {
842 Record *Op = OperatorMap[N->getName()];
843 // Transform GlobalAddress to TargetGlobalAddress
844 if (Op && (Op->getName() == "globaladdr" ||
845 Op->getName() == "globaltlsaddr")) {
Scott Michel30124c22008-01-29 02:29:31 +0000846 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +0000847 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000848 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
849 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
850 ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
852 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000853 Val = TmpVar;
854 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000855 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000856 NodeOps.push_back(Val);
Scott Michel30124c22008-01-29 02:29:31 +0000857 } else if (!N->isLeaf()
858 && (N->getOperator()->getName() == "texternalsym"
859 || N->getOperator()->getName() == "tconstpool")) {
860 // Do not rewrite the variable name, since we don't generate a new
861 // temporary.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 NodeOps.push_back(Val);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000863 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000864 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
Dan Gohmanba5cbd92009-01-16 02:05:52 +0000865 NodeOps.push_back("CPTmp" + Val + "_" + utostr(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000866 }
867 } else {
868 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
869 // node even if it isn't one. Don't select it.
870 if (!LikeLeaf) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000871 if (isRoot && N->isLeaf()) {
872 emitCode("ReplaceUses(N, " + Val + ");");
873 emitCode("return NULL;");
874 }
875 }
876 NodeOps.push_back(Val);
877 }
Scott Michel30124c22008-01-29 02:29:31 +0000878
879 if (ModifiedVal) {
880 VariableMap[VarName] = Val;
881 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882 return NodeOps;
883 }
884 if (N->isLeaf()) {
885 // If this is an explicit register reference, handle it.
886 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
887 unsigned ResNo = TmpNo++;
888 if (DI->getDef()->isSubClassOf("Register")) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000889 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000890 getQualifiedName(DI->getDef()) + ", " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000891 getEnumName(N->getTypeNum(0)) + ");");
892 NodeOps.push_back("Tmp" + utostr(ResNo));
893 return NodeOps;
894 } else if (DI->getDef()->getName() == "zero_reg") {
Dan Gohman8181bd12008-07-27 21:46:04 +0000895 emitCode("SDValue Tmp" + utostr(ResNo) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896 " = CurDAG->getRegister(0, " +
897 getEnumName(N->getTypeNum(0)) + ");");
898 NodeOps.push_back("Tmp" + utostr(ResNo));
899 return NodeOps;
900 }
901 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
902 unsigned ResNo = TmpNo++;
903 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
Dan Gohman8181bd12008-07-27 21:46:04 +0000904 emitCode("SDValue Tmp" + utostr(ResNo) +
Scott Michelac7091c2008-02-15 23:05:48 +0000905 " = CurDAG->getTargetConstant(0x" + itohexstr(II->getValue()) +
906 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000907 NodeOps.push_back("Tmp" + utostr(ResNo));
908 return NodeOps;
909 }
910
911#ifndef NDEBUG
912 N->dump();
913#endif
914 assert(0 && "Unknown leaf type!");
915 return NodeOps;
916 }
917
918 Record *Op = N->getOperator();
919 if (Op->isSubClassOf("Instruction")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000920 const CodeGenTarget &CGT = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000922 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattner7c6e5852008-01-06 01:52:22 +0000923 const TreePattern *InstPat = Inst.getPattern();
Evan Chengf031fcb2007-09-25 01:48:59 +0000924 // FIXME: Assume actual pattern comes before "implicit".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000925 TreePatternNode *InstPatNode =
Evan Cheng775baac2007-09-12 23:30:14 +0000926 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
927 : (InstPat ? InstPat->getTree(0) : NULL);
Dan Gohmana4ce3632009-01-16 21:30:55 +0000928 if (InstPatNode && !InstPatNode->isLeaf() &&
929 InstPatNode->getOperator()->getName() == "set") {
Evan Chengf37df842007-09-11 19:52:18 +0000930 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000931 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000932 bool IsVariadic = isRoot && II.isVariadic;
Evan Cheng775baac2007-09-12 23:30:14 +0000933 // FIXME: fix how we deal with physical register operands.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng775baac2007-09-12 23:30:14 +0000935 bool HasImpResults = isRoot && DstRegs.size() > 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000936 bool NodeHasOptInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000937 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 bool NodeHasInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000939 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengdec1dd12007-09-07 23:59:02 +0000940 bool NodeHasOutFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000941 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 bool NodeHasChain = InstPatNode &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000943 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 bool InputHasChain = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000945 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000946 unsigned NumResults = Inst.getNumResults();
Evan Cheng775baac2007-09-12 23:30:14 +0000947 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000949 // Record output varargs info.
950 OutputIsVariadic = IsVariadic;
951
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000952 if (NodeHasOptInFlag) {
953 emitCode("bool HasInFlag = "
954 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
955 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000956 if (IsVariadic)
Dan Gohman8181bd12008-07-27 21:46:04 +0000957 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000958
959 // How many results is this pattern expected to produce?
Evan Cheng775baac2007-09-12 23:30:14 +0000960 unsigned NumPatResults = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000961 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
Duncan Sands92c43912008-06-06 12:08:01 +0000962 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng775baac2007-09-12 23:30:14 +0000964 NumPatResults++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000965 }
966
967 if (OrigChains.size() > 0) {
968 // The original input chain is being ignored. If it is not just
969 // pointing to the op that's being folded, we should create a
970 // TokenFactor with it and the chain of the folded op as the new chain.
971 // We could potentially be doing multiple levels of folding, in that
972 // case, the TokenFactor can have more operands.
Dan Gohman8181bd12008-07-27 21:46:04 +0000973 emitCode("SmallVector<SDValue, 8> InChains;");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000974 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
Gabor Greif1c80d112008-08-28 21:40:38 +0000975 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
976 OrigChains[i].second + ".getNode()) {");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000977 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
978 emitCode("}");
979 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000980 emitCode("InChains.push_back(" + ChainName + ");");
981 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
982 "&InChains[0], InChains.size());");
David Greene932618b2008-10-27 21:56:29 +0000983 if (GenDebug) {
984 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
985 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
986 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000987 }
988
989 // Loop over all of the operands of the instruction pattern, emitting code
990 // to fill them all in. The node 'N' usually has number children equal to
991 // the number of input operands of the instruction. However, in cases
992 // where there are predicate operands for an instruction, we need to fill
993 // in the 'execute always' values. Match up the node operands to the
994 // instruction operands to do this.
995 std::vector<std::string> AllOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000996 for (unsigned ChildNo = 0, InstOpNo = NumResults;
997 InstOpNo != II.OperandList.size(); ++InstOpNo) {
998 std::vector<std::string> Ops;
999
Dan Gohman3329ffe2008-05-29 19:57:41 +00001000 // Determine what to emit for this operand.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001 Record *OperandNode = II.OperandList[InstOpNo].Rec;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001002 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1003 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1004 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Dan Gohman3329ffe2008-05-29 19:57:41 +00001005 // This is a predicate or optional def operand; emit the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001006 // 'default ops' operands.
1007 const DAGDefaultOperand &DefaultOp =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001008 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001009 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Chengdb1f2462007-09-17 22:26:41 +00001010 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 InFlagDecled, ResNodeDecled);
1012 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 }
Dan Gohman3329ffe2008-05-29 19:57:41 +00001014 } else {
1015 // Otherwise this is a normal operand or a predicate operand without
1016 // 'execute always'; emit it.
1017 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1018 InFlagDecled, ResNodeDecled);
1019 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1020 ++ChildNo;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001021 }
1022 }
1023
1024 // Emit all the chain and CopyToReg stuff.
1025 bool ChainEmitted = NodeHasChain;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001026 if (NodeHasInFlag || HasImpInputs)
1027 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1028 InFlagDecled, ResNodeDecled, true);
1029 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1030 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001031 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 InFlagDecled = true;
1033 }
1034 if (NodeHasOptInFlag) {
1035 emitCode("if (HasInFlag) {");
1036 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 emitCode("}");
1038 }
1039 }
1040
1041 unsigned ResNo = TmpNo++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001042
Dan Gohman6761ff52008-07-07 21:00:17 +00001043 unsigned OpsNo = OpcNo;
1044 std::string CodePrefix;
1045 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1046 std::deque<std::string> After;
1047 std::string NodeName;
1048 if (!isRoot) {
1049 NodeName = "Tmp" + utostr(ResNo);
Dan Gohman8181bd12008-07-27 21:46:04 +00001050 CodePrefix = "SDValue " + NodeName + "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 } else {
Dan Gohman6761ff52008-07-07 21:00:17 +00001052 NodeName = "ResNode";
1053 if (!ResNodeDecled) {
1054 CodePrefix = "SDNode *" + NodeName + " = ";
1055 ResNodeDecled = true;
1056 } else
1057 CodePrefix = NodeName + " = ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058 }
1059
Dan Gohman6761ff52008-07-07 21:00:17 +00001060 std::string Code = "Opc" + utostr(OpcNo);
1061
Bill Wendling66968012009-01-29 05:27:31 +00001062 if (!isRoot || (InputHasChain && !NodeHasChain))
Bill Wendling7ebe88a2009-01-29 23:19:43 +00001063 // For call to "getTargetNode()".
Bill Wendling66968012009-01-29 05:27:31 +00001064 Code += ", N.getDebugLoc()";
1065
Dan Gohman6761ff52008-07-07 21:00:17 +00001066 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1067
1068 // Output order: results, chain, flags
1069 // Result types.
1070 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1071 Code += ", VT" + utostr(VTNo);
1072 emitVT(getEnumName(N->getTypeNum(0)));
1073 }
1074 // Add types for implicit results in physical registers, scheduler will
1075 // care of adding copyfromreg nodes.
1076 for (unsigned i = 0; i < NumDstRegs; i++) {
1077 Record *RR = DstRegs[i];
1078 if (RR->isSubClassOf("Register")) {
1079 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1080 Code += ", " + getEnumName(RVT);
1081 }
1082 }
1083 if (NodeHasChain)
1084 Code += ", MVT::Other";
1085 if (NodeHasOutFlag)
1086 Code += ", MVT::Flag";
1087
1088 // Inputs.
1089 if (IsVariadic) {
1090 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1091 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1092 AllOps.clear();
1093
1094 // Figure out whether any operands at the end of the op list are not
1095 // part of the variable section.
1096 std::string EndAdjust;
1097 if (NodeHasInFlag || HasImpInputs)
1098 EndAdjust = "-1"; // Always has one flag.
1099 else if (NodeHasOptInFlag)
1100 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1101
1102 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1103 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1104
Dan Gohman6761ff52008-07-07 21:00:17 +00001105 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1106 emitCode("}");
1107 }
1108
1109 // Generate MemOperandSDNodes nodes for each memory accesses covered by
1110 // this pattern.
Dan Gohmanbc1714f2008-12-03 02:30:17 +00001111 if (II.mayLoad | II.mayStore) {
Dan Gohman6761ff52008-07-07 21:00:17 +00001112 std::vector<std::string>::const_iterator mi, mie;
1113 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
David Greene932618b2008-10-27 21:56:29 +00001114 std::string LSIName = "LSI_" + *mi;
1115 emitCode("SDValue " + LSIName + " = "
Dan Gohman6761ff52008-07-07 21:00:17 +00001116 "CurDAG->getMemOperand(cast<MemSDNode>(" +
1117 *mi + ")->getMemOperand());");
David Greene932618b2008-10-27 21:56:29 +00001118 if (GenDebug) {
1119 emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"yellow\");");
1120 emitCode("CurDAG->setSubgraphColor(" + LSIName +".getNode(), \"black\");");
1121 }
Dan Gohman6761ff52008-07-07 21:00:17 +00001122 if (IsVariadic)
David Greene932618b2008-10-27 21:56:29 +00001123 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + LSIName + ");");
Dan Gohman6761ff52008-07-07 21:00:17 +00001124 else
David Greene932618b2008-10-27 21:56:29 +00001125 AllOps.push_back(LSIName);
Dan Gohman6761ff52008-07-07 21:00:17 +00001126 }
1127 }
1128
1129 if (NodeHasChain) {
1130 if (IsVariadic)
1131 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1132 else
1133 AllOps.push_back(ChainName);
1134 }
1135
1136 if (IsVariadic) {
1137 if (NodeHasInFlag || HasImpInputs)
1138 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1139 else if (NodeHasOptInFlag) {
1140 emitCode("if (HasInFlag)");
1141 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1142 }
1143 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1144 ".size()";
1145 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1146 AllOps.push_back("InFlag");
1147
1148 unsigned NumOps = AllOps.size();
1149 if (NumOps) {
1150 if (!NodeHasOptInFlag && NumOps < 4) {
1151 for (unsigned i = 0; i != NumOps; ++i)
1152 Code += ", " + AllOps[i];
1153 } else {
Dan Gohman8181bd12008-07-27 21:46:04 +00001154 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
Dan Gohman6761ff52008-07-07 21:00:17 +00001155 for (unsigned i = 0; i != NumOps; ++i) {
1156 OpsCode += AllOps[i];
1157 if (i != NumOps-1)
1158 OpsCode += ", ";
1159 }
1160 emitCode(OpsCode + " };");
1161 Code += ", Ops" + utostr(OpsNo) + ", ";
1162 if (NodeHasOptInFlag) {
1163 Code += "HasInFlag ? ";
1164 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1165 } else
1166 Code += utostr(NumOps);
1167 }
1168 }
1169
1170 if (!isRoot)
1171 Code += "), 0";
1172
Dan Gohmanbd68c792008-07-17 19:10:17 +00001173 std::vector<std::string> ReplaceFroms;
1174 std::vector<std::string> ReplaceTos;
Dan Gohman6761ff52008-07-07 21:00:17 +00001175 if (!isRoot) {
1176 NodeOps.push_back("Tmp" + utostr(ResNo));
1177 } else {
1178
1179 if (NodeHasOutFlag) {
1180 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001181 After.push_back("SDValue InFlag(ResNode, " +
Dan Gohman6761ff52008-07-07 21:00:17 +00001182 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1183 ");");
1184 InFlagDecled = true;
1185 } else
Dan Gohman8181bd12008-07-27 21:46:04 +00001186 After.push_back("InFlag = SDValue(ResNode, " +
Dan Gohman6761ff52008-07-07 21:00:17 +00001187 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1188 ");");
1189 }
1190
Dan Gohman700c4b32009-01-05 19:31:28 +00001191 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1192 ReplaceFroms.push_back("SDValue(" +
1193 FoldedChains[j].first + ".getNode(), " +
1194 utostr(FoldedChains[j].second) +
1195 ")");
1196 ReplaceTos.push_back("SDValue(ResNode, " +
1197 utostr(NumResults+NumDstRegs) + ")");
Dan Gohman6761ff52008-07-07 21:00:17 +00001198 }
1199
1200 if (NodeHasOutFlag) {
1201 if (FoldedFlag.first != "") {
Gabor Greif1c80d112008-08-28 21:40:38 +00001202 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001203 utostr(FoldedFlag.second) + ")");
1204 ReplaceTos.push_back("InFlag");
Dan Gohman6761ff52008-07-07 21:00:17 +00001205 } else {
1206 assert(NodeHasProperty(Pattern, SDNPOutFlag, CGP));
Gabor Greif1c80d112008-08-28 21:40:38 +00001207 ReplaceFroms.push_back("SDValue(N.getNode(), " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001208 utostr(NumPatResults + (unsigned)InputHasChain)
1209 + ")");
1210 ReplaceTos.push_back("InFlag");
Dan Gohman6761ff52008-07-07 21:00:17 +00001211 }
Dan Gohman6761ff52008-07-07 21:00:17 +00001212 }
1213
Dan Gohmanbd68c792008-07-17 19:10:17 +00001214 if (!ReplaceFroms.empty() && InputHasChain) {
Gabor Greif1c80d112008-08-28 21:40:38 +00001215 ReplaceFroms.push_back("SDValue(N.getNode(), " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001216 utostr(NumPatResults) + ")");
Gabor Greif1c80d112008-08-28 21:40:38 +00001217 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
Gabor Greif46bf5472008-08-26 22:36:50 +00001218 ChainName + ".getResNo()" + ")");
Dan Gohman6761ff52008-07-07 21:00:17 +00001219 ChainAssignmentNeeded |= NodeHasChain;
1220 }
1221
1222 // User does not expect the instruction would produce a chain!
1223 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1224 ;
1225 } else if (InputHasChain && !NodeHasChain) {
1226 // One of the inner node produces a chain.
Dan Gohmanbd68c792008-07-17 19:10:17 +00001227 if (NodeHasOutFlag) {
Gabor Greif1c80d112008-08-28 21:40:38 +00001228 ReplaceFroms.push_back("SDValue(N.getNode(), " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001229 utostr(NumPatResults+1) +
1230 ")");
Gabor Greif46bf5472008-08-26 22:36:50 +00001231 ReplaceTos.push_back("SDValue(ResNode, N.getResNo()-1)");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001232 }
Gabor Greif1c80d112008-08-28 21:40:38 +00001233 ReplaceFroms.push_back("SDValue(N.getNode(), " +
Dan Gohmanbd68c792008-07-17 19:10:17 +00001234 utostr(NumPatResults) + ")");
1235 ReplaceTos.push_back(ChainName);
Dan Gohman6761ff52008-07-07 21:00:17 +00001236 }
1237 }
1238
1239 if (ChainAssignmentNeeded) {
1240 // Remember which op produces the chain.
1241 std::string ChainAssign;
1242 if (!isRoot)
Dan Gohman8181bd12008-07-27 21:46:04 +00001243 ChainAssign = ChainName + " = SDValue(" + NodeName +
Gabor Greif1c80d112008-08-28 21:40:38 +00001244 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
Dan Gohman6761ff52008-07-07 21:00:17 +00001245 else
Dan Gohman8181bd12008-07-27 21:46:04 +00001246 ChainAssign = ChainName + " = SDValue(" + NodeName +
Dan Gohman6761ff52008-07-07 21:00:17 +00001247 ", " + utostr(NumResults+NumDstRegs) + ");";
1248
1249 After.push_front(ChainAssign);
1250 }
1251
Dan Gohmanbd68c792008-07-17 19:10:17 +00001252 if (ReplaceFroms.size() == 1) {
1253 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1254 ReplaceTos[0] + ");");
1255 } else if (!ReplaceFroms.empty()) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001256 After.push_back("const SDValue Froms[] = {");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001257 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1258 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1259 After.push_back("};");
Dan Gohman8181bd12008-07-27 21:46:04 +00001260 After.push_back("const SDValue Tos[] = {");
Dan Gohmanbd68c792008-07-17 19:10:17 +00001261 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1262 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1263 After.push_back("};");
1264 After.push_back("ReplaceUses(Froms, Tos, " +
1265 itostr(ReplaceFroms.size()) + ");");
1266 }
1267
1268 // We prefer to use SelectNodeTo since it avoids allocation when
1269 // possible and it avoids CSE map recalculation for the node's
1270 // users, however it's tricky to use in a non-root context.
Dan Gohman6761ff52008-07-07 21:00:17 +00001271 //
Dan Gohmanbd68c792008-07-17 19:10:17 +00001272 // We also don't use if the pattern replacement is being used to
1273 // jettison a chain result, since morphing the node in place
1274 // would leave users of the chain dangling.
Dan Gohman6761ff52008-07-07 21:00:17 +00001275 //
Dan Gohmanbd68c792008-07-17 19:10:17 +00001276 if (!isRoot || (InputHasChain && !NodeHasChain)) {
Dan Gohman6761ff52008-07-07 21:00:17 +00001277 Code = "CurDAG->getTargetNode(" + Code;
1278 } else {
Gabor Greif1c80d112008-08-28 21:40:38 +00001279 Code = "CurDAG->SelectNodeTo(N.getNode(), " + Code;
Dan Gohman6761ff52008-07-07 21:00:17 +00001280 }
1281 if (isRoot) {
1282 if (After.empty())
1283 CodePrefix = "return ";
1284 else
1285 After.push_back("return ResNode;");
1286 }
1287
1288 emitCode(CodePrefix + Code + ");");
David Greene932618b2008-10-27 21:56:29 +00001289
1290 if (GenDebug) {
1291 if (!isRoot) {
1292 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"yellow\");");
1293 emitCode("CurDAG->setSubgraphColor(" + NodeName +".getNode(), \"black\");");
1294 }
1295 else {
1296 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1297 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1298 }
1299 }
1300
Dan Gohman6761ff52008-07-07 21:00:17 +00001301 for (unsigned i = 0, e = After.size(); i != e; ++i)
1302 emitCode(After[i]);
1303
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001304 return NodeOps;
Dan Gohman5394e112008-10-15 06:17:21 +00001305 }
1306 if (Op->isSubClassOf("SDNodeXForm")) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001307 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1308 // PatLeaf node - the operand may or may not be a leaf node. But it should
1309 // behave like one.
1310 std::vector<std::string> Ops =
Evan Chengdb1f2462007-09-17 22:26:41 +00001311 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 ResNodeDecled, true);
1313 unsigned ResNo = TmpNo++;
Dan Gohman8181bd12008-07-27 21:46:04 +00001314 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
Gabor Greif1c80d112008-08-28 21:40:38 +00001315 + "(" + Ops.back() + ".getNode());");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 NodeOps.push_back("Tmp" + utostr(ResNo));
1317 if (isRoot)
Gabor Greif1c80d112008-08-28 21:40:38 +00001318 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001319 return NodeOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320 }
Dan Gohman5394e112008-10-15 06:17:21 +00001321
1322 N->dump();
1323 cerr << "\n";
1324 throw std::string("Unknown node in result pattern!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001325 }
1326
1327 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1328 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1329 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1330 /// for, this returns true otherwise false if Pat has all types.
1331 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1332 const std::string &Prefix, bool isRoot = false) {
1333 // Did we find one?
1334 if (Pat->getExtTypes() != Other->getExtTypes()) {
1335 // Move a type over from 'other' to 'pat'.
1336 Pat->setTypes(Other->getExtTypes());
1337 // The top level node type is checked outside of the select function.
1338 if (!isRoot)
Gabor Greif1c80d112008-08-28 21:40:38 +00001339 emitCheck(Prefix + ".getNode()->getValueType(0) == " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001340 getName(Pat->getTypeNum(0)));
1341 return true;
1342 }
1343
1344 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001345 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001346 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1347 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1348 Prefix + utostr(OpNo)))
1349 return true;
1350 return false;
1351 }
1352
1353private:
1354 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1355 /// being built.
1356 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1357 bool &ChainEmitted, bool &InFlagDecled,
1358 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001359 const CodeGenTarget &T = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001360 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001361 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1362 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1364 TreePatternNode *Child = N->getChild(i);
1365 if (!Child->isLeaf()) {
1366 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1367 InFlagDecled, ResNodeDecled);
1368 } else {
1369 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1370 if (!Child->getName().empty()) {
1371 std::string Name = RootName + utostr(OpNo);
1372 if (Duplicates.find(Name) != Duplicates.end())
1373 // A duplicate! Do not emit a copy for this node.
1374 continue;
1375 }
1376
1377 Record *RR = DI->getDef();
1378 if (RR->isSubClassOf("Register")) {
Duncan Sands92c43912008-06-06 12:08:01 +00001379 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 if (RVT == MVT::Flag) {
1381 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001382 emitCode("SDValue InFlag = " + RootName + utostr(OpNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001383 InFlagDecled = true;
1384 } else
1385 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001386 } else {
1387 if (!ChainEmitted) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001388 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001389 ChainName = "Chain";
1390 ChainEmitted = true;
1391 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001392 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001393 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001394 InFlagDecled = true;
1395 }
1396 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1397 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dale Johannesenb03cc3f2009-02-04 23:02:30 +00001398 ", " + RootName + ".getDebugLoc()" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001399 ", " + getQualifiedName(RR) +
Gabor Greif1c80d112008-08-28 21:40:38 +00001400 ", " + RootName + utostr(OpNo) + ", InFlag).getNode();");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001401 ResNodeDecled = true;
Dan Gohman8181bd12008-07-27 21:46:04 +00001402 emitCode(ChainName + " = SDValue(ResNode, 0);");
1403 emitCode("InFlag = SDValue(ResNode, 1);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001404 }
1405 }
1406 }
1407 }
1408 }
1409
1410 if (HasInFlag) {
1411 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +00001412 emitCode("SDValue InFlag = " + RootName +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001413 ".getOperand(" + utostr(OpNo) + ");");
1414 InFlagDecled = true;
1415 } else
1416 emitCode("InFlag = " + RootName +
1417 ".getOperand(" + utostr(OpNo) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 }
1419 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001420};
1421
1422/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1423/// stream to match the pattern, and generate the code for the match if it
1424/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001425void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001426 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1427 std::set<std::string> &GeneratedDecl,
1428 std::vector<std::string> &TargetOpcodes,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001429 std::vector<std::string> &TargetVTs,
1430 bool &OutputIsVariadic,
1431 unsigned &NumInputRootOps) {
1432 OutputIsVariadic = false;
1433 NumInputRootOps = 0;
1434
Dan Gohmane97f1a32008-08-22 00:20:26 +00001435 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001436 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1437 GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001438 TargetOpcodes, TargetVTs,
1439 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001440
1441 // Emit the matcher, capturing named arguments in VariableMap.
1442 bool FoundChain = false;
1443 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1444
1445 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner14948ea2008-01-05 22:58:54 +00001446 TreePattern &TP = *CGP.pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001447
1448 // At this point, we know that we structurally match the pattern, but the
1449 // types of the nodes may not match. Figure out the fewest number of type
1450 // comparisons we need to emit. For example, if there is only one integer
1451 // type supported by a target, there should be no type comparisons at all for
1452 // integer patterns!
1453 //
1454 // To figure out the fewest number of type checks needed, clone the pattern,
1455 // remove the types, then perform type inference on the pattern as a whole.
1456 // If there are unresolved types, emit an explicit check for those types,
1457 // apply the type to the tree, then rerun type inference. Iterate until all
1458 // types are resolved.
1459 //
1460 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1461 RemoveAllTypes(Pat);
1462
1463 do {
1464 // Resolve/propagate as many types as possible.
1465 try {
1466 bool MadeChange = true;
1467 while (MadeChange)
1468 MadeChange = Pat->ApplyTypeConstraints(TP,
1469 true/*Ignore reg constraints*/);
1470 } catch (...) {
1471 assert(0 && "Error: could not find consistent types for something we"
1472 " already decided was ok!");
1473 abort();
1474 }
1475
1476 // Insert a check for an unresolved type and add it to the tree. If we find
1477 // an unresolved type to add a check for, this returns true and we iterate,
1478 // otherwise we are done.
1479 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1480
Evan Cheng775baac2007-09-12 23:30:14 +00001481 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001482 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001483 delete Pat;
1484}
1485
1486/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1487/// a line causes any of them to be empty, remove them and return true when
1488/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001489static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001490 std::vector<std::pair<unsigned, std::string> > > >
1491 &Patterns) {
1492 bool ErasedPatterns = false;
1493 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1494 Patterns[i].second.pop_back();
1495 if (Patterns[i].second.empty()) {
1496 Patterns.erase(Patterns.begin()+i);
1497 --i; --e;
1498 ErasedPatterns = true;
1499 }
1500 }
1501 return ErasedPatterns;
1502}
1503
1504/// EmitPatterns - Emit code for at least one pattern, but try to group common
1505/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001506void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001507 std::vector<std::pair<unsigned, std::string> > > >
1508 &Patterns, unsigned Indent,
1509 std::ostream &OS) {
1510 typedef std::pair<unsigned, std::string> CodeLine;
1511 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001512 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513
1514 if (Patterns.empty()) return;
1515
1516 // Figure out how many patterns share the next code line. Explicitly copy
1517 // FirstCodeLine so that we don't invalidate a reference when changing
1518 // Patterns.
1519 const CodeLine FirstCodeLine = Patterns.back().second.back();
1520 unsigned LastMatch = Patterns.size()-1;
1521 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1522 --LastMatch;
1523
1524 // If not all patterns share this line, split the list into two pieces. The
1525 // first chunk will use this line, the second chunk won't.
1526 if (LastMatch != 0) {
1527 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1528 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1529
1530 // FIXME: Emit braces?
1531 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001532 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001533 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1534 Pattern.getSrcPattern()->print(OS);
1535 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1536 Pattern.getDstPattern()->print(OS);
1537 OS << "\n";
1538 unsigned AddedComplexity = Pattern.getAddedComplexity();
1539 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001540 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001541 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001542 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001543 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001544 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001545 }
1546 if (FirstCodeLine.first != 1) {
1547 OS << std::string(Indent, ' ') << "{\n";
1548 Indent += 2;
1549 }
1550 EmitPatterns(Shared, Indent, OS);
1551 if (FirstCodeLine.first != 1) {
1552 Indent -= 2;
1553 OS << std::string(Indent, ' ') << "}\n";
1554 }
1555
1556 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001557 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1559 Pattern.getSrcPattern()->print(OS);
1560 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1561 Pattern.getDstPattern()->print(OS);
1562 OS << "\n";
1563 unsigned AddedComplexity = Pattern.getAddedComplexity();
1564 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001565 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001566 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001567 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001568 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001569 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001570 }
1571 EmitPatterns(Other, Indent, OS);
1572 return;
1573 }
1574
1575 // Remove this code from all of the patterns that share it.
1576 bool ErasedPatterns = EraseCodeLine(Patterns);
1577
1578 bool isPredicate = FirstCodeLine.first == 1;
1579
1580 // Otherwise, every pattern in the list has this line. Emit it.
1581 if (!isPredicate) {
1582 // Normal code.
1583 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1584 } else {
1585 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1586
1587 // If the next code line is another predicate, and if all of the pattern
1588 // in this group share the same next line, emit it inline now. Do this
1589 // until we run out of common predicates.
1590 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1591 // Check that all of fhe patterns in Patterns end with the same predicate.
1592 bool AllEndWithSamePredicate = true;
1593 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1594 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1595 AllEndWithSamePredicate = false;
1596 break;
1597 }
1598 // If all of the predicates aren't the same, we can't share them.
1599 if (!AllEndWithSamePredicate) break;
1600
1601 // Otherwise we can. Emit it shared now.
1602 OS << " &&\n" << std::string(Indent+4, ' ')
1603 << Patterns.back().second.back().second;
1604 ErasedPatterns = EraseCodeLine(Patterns);
1605 }
1606
1607 OS << ") {\n";
1608 Indent += 2;
1609 }
1610
1611 EmitPatterns(Patterns, Indent, OS);
1612
1613 if (isPredicate)
1614 OS << std::string(Indent-2, ' ') << "}\n";
1615}
1616
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001617static std::string getLegalCName(std::string OpName) {
1618 std::string::size_type pos = OpName.find("::");
1619 if (pos != std::string::npos)
1620 OpName.replace(pos, 2, "_");
1621 return OpName;
1622}
1623
1624void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001625 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001626
Dan Gohman6a36cc92008-08-20 21:45:57 +00001627 // Get the namespace to insert instructions into.
1628 std::string InstNS = Target.getInstNamespace();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 if (!InstNS.empty()) InstNS += "::";
1630
1631 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001632 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633 // All unique target node emission functions.
1634 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerae506702008-01-06 01:10:31 +00001635 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001636 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001637 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001638
1639 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640 if (!Node->isLeaf()) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001641 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001642 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001643 } else {
1644 const ComplexPattern *CP;
1645 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001646 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001647 push_back(&Pattern);
Chris Lattner14948ea2008-01-05 22:58:54 +00001648 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 std::vector<Record*> OpNodes = CP->getRootNodes();
1650 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001651 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1652 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001653 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 }
1655 } else {
1656 cerr << "Unrecognized opcode '";
1657 Node->dump();
1658 cerr << "' on tree pattern '";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001659 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 exit(1);
1661 }
1662 }
1663 }
1664
1665 // For each opcode, there might be multiple select functions, one per
1666 // ValueType of the node (or its first operand if it doesn't produce a
1667 // non-chain result.
1668 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1669
1670 // Emit one Select_* method for each top-level opcode. We do this instead of
1671 // emitting one giant switch statement to support compilers where this will
1672 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001673 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001674 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1675 PBOI != E; ++PBOI) {
1676 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001677 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001678 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1679
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001680 // Split them into groups by type.
Duncan Sands92c43912008-06-06 12:08:01 +00001681 std::map<MVT::SimpleValueType,
1682 std::vector<const PatternToMatch*> > PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001684 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001685 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner4a5394e2008-08-26 07:01:28 +00001686 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001687 }
1688
Duncan Sands92c43912008-06-06 12:08:01 +00001689 for (std::map<MVT::SimpleValueType,
1690 std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1692 ++II) {
Duncan Sands92c43912008-06-06 12:08:01 +00001693 MVT::SimpleValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001694 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman5394e112008-10-15 06:17:21 +00001695 typedef std::pair<unsigned, std::string> CodeLine;
1696 typedef std::vector<CodeLine> CodeList;
1697 typedef CodeList::iterator CodeListI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698
Chris Lattner81915752008-01-05 22:30:17 +00001699 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 std::vector<std::vector<std::string> > PatternOpcodes;
1701 std::vector<std::vector<std::string> > PatternVTs;
1702 std::vector<std::set<std::string> > PatternDecls;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001703 std::vector<bool> OutputIsVariadicFlags;
1704 std::vector<unsigned> NumInputRootOpsCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001705 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1706 CodeList GeneratedCode;
1707 std::set<std::string> GeneratedDecl;
1708 std::vector<std::string> TargetOpcodes;
1709 std::vector<std::string> TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001710 bool OutputIsVariadic;
1711 unsigned NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001713 TargetOpcodes, TargetVTs,
1714 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001715 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1716 PatternDecls.push_back(GeneratedDecl);
1717 PatternOpcodes.push_back(TargetOpcodes);
1718 PatternVTs.push_back(TargetVTs);
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001719 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1720 NumInputRootOpsCounts.push_back(NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001721 }
1722
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 // Factor target node emission code (emitted by EmitResultCode) into
1724 // separate functions. Uniquing and share them among all instruction
1725 // selection routines.
1726 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1727 CodeList &GeneratedCode = CodeForPatterns[i].second;
1728 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1729 std::vector<std::string> &TargetVTs = PatternVTs[i];
1730 std::set<std::string> Decls = PatternDecls[i];
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001731 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1732 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 std::vector<std::string> AddedInits;
1734 int CodeSize = (int)GeneratedCode.size();
1735 int LastPred = -1;
1736 for (int j = CodeSize-1; j >= 0; --j) {
1737 if (LastPred == -1 && GeneratedCode[j].first == 1)
1738 LastPred = j;
1739 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1740 AddedInits.push_back(GeneratedCode[j].second);
1741 }
1742
Dan Gohman8181bd12008-07-27 21:46:04 +00001743 std::string CalleeCode = "(const SDValue &N";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001744 std::string CallerCode = "(N";
1745 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1746 CalleeCode += ", unsigned Opc" + utostr(j);
1747 CallerCode += ", " + TargetOpcodes[j];
1748 }
1749 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Duncan Sands92c43912008-06-06 12:08:01 +00001750 CalleeCode += ", MVT VT" + utostr(j);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001751 CallerCode += ", " + TargetVTs[j];
1752 }
1753 for (std::set<std::string>::iterator
1754 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1755 std::string Name = *I;
Dan Gohman8181bd12008-07-27 21:46:04 +00001756 CalleeCode += ", SDValue &" + Name;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001757 CallerCode += ", " + Name;
1758 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001759
1760 if (OutputIsVariadic) {
1761 CalleeCode += ", unsigned NumInputRootOps";
1762 CallerCode += ", " + utostr(NumInputRootOps);
1763 }
1764
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001765 CallerCode += ");";
1766 CalleeCode += ") ";
1767 // Prevent emission routines from being inlined to reduce selection
1768 // routines stack frame sizes.
1769 CalleeCode += "DISABLE_INLINE ";
1770 CalleeCode += "{\n";
1771
1772 for (std::vector<std::string>::const_reverse_iterator
1773 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1774 CalleeCode += " " + *I + "\n";
1775
1776 for (int j = LastPred+1; j < CodeSize; ++j)
1777 CalleeCode += " " + GeneratedCode[j].second + "\n";
1778 for (int j = LastPred+1; j < CodeSize; ++j)
1779 GeneratedCode.pop_back();
1780 CalleeCode += "}\n";
1781
1782 // Uniquing the emission routines.
1783 unsigned EmitFuncNum;
1784 std::map<std::string, unsigned>::iterator EFI =
1785 EmitFunctions.find(CalleeCode);
1786 if (EFI != EmitFunctions.end()) {
1787 EmitFuncNum = EFI->second;
1788 } else {
1789 EmitFuncNum = EmitFunctions.size();
1790 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1791 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1792 }
1793
1794 // Replace the emission code within selection routines with calls to the
1795 // emission functions.
David Greene932618b2008-10-27 21:56:29 +00001796 if (GenDebug) {
1797 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"red\");"));
1798 }
1799 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1800 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1801 if (GenDebug) {
1802 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1803 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1804 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1805 GeneratedCode.push_back(std::make_pair(0, "}"));
1806 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N.getNode(), \"black\");"));
1807 }
1808 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001809 }
1810
1811 // Print function.
1812 std::string OpVTStr;
1813 if (OpVT == MVT::iPTR) {
1814 OpVTStr = "_iPTR";
Mon P Wangce3ac892008-07-30 04:36:53 +00001815 } else if (OpVT == MVT::iPTRAny) {
1816 OpVTStr = "_iPTRAny";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817 } else if (OpVT == MVT::isVoid) {
1818 // Nodes with a void result actually have a first result type of either
1819 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1820 // void to this case, we handle it specially here.
1821 } else {
1822 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1823 }
1824 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1825 OpcodeVTMap.find(OpName);
1826 if (OpVTI == OpcodeVTMap.end()) {
1827 std::vector<std::string> VTSet;
1828 VTSet.push_back(OpVTStr);
1829 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1830 } else
1831 OpVTI->second.push_back(OpVTStr);
1832
Dan Gohman5394e112008-10-15 06:17:21 +00001833 // We want to emit all of the matching code now. However, we want to emit
1834 // the matches in order of minimal cost. Sort the patterns so the least
1835 // cost one is at the start.
1836 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1837 PatternSortingPredicate(CGP));
1838
1839 // Scan the code to see if all of the patterns are reachable and if it is
1840 // possible that the last one might not match.
1841 bool mightNotMatch = true;
1842 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1843 CodeList &GeneratedCode = CodeForPatterns[i].second;
1844 mightNotMatch = false;
1845
1846 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1847 if (GeneratedCode[j].first == 1) { // predicate.
1848 mightNotMatch = true;
1849 break;
1850 }
1851 }
1852
1853 // If this pattern definitely matches, and if it isn't the last one, the
1854 // patterns after it CANNOT ever match. Error out.
1855 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1856 cerr << "Pattern '";
1857 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1858 cerr << "' is impossible to select!\n";
1859 exit(1);
1860 }
1861 }
1862
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001863 // Loop through and reverse all of the CodeList vectors, as we will be
1864 // accessing them from their logical front, but accessing the end of a
1865 // vector is more efficient.
1866 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1867 CodeList &GeneratedCode = CodeForPatterns[i].second;
1868 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1869 }
1870
1871 // Next, reverse the list of patterns itself for the same reason.
1872 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1873
Dan Gohman4b975a92009-01-29 01:37:18 +00001874 OS << "SDNode *Select_" << getLegalCName(OpName)
1875 << OpVTStr << "(const SDValue &N) {\n";
1876
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001877 // Emit all of the patterns now, grouped together to share code.
1878 EmitPatterns(CodeForPatterns, 2, OS);
1879
1880 // If the last pattern has predicates (which could fail) emit code to
1881 // catch the case where nothing handles a pattern.
1882 if (mightNotMatch) {
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001883 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001884 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1885 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001886 OpName != "ISD::INTRINSIC_VOID")
1887 OS << " CannotYetSelect(N);\n";
1888 else
1889 OS << " CannotYetSelectIntrinsic(N);\n";
1890
1891 OS << " return NULL;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001892 }
1893 OS << "}\n\n";
1894 }
1895 }
1896
1897 // Emit boilerplate.
Dan Gohman8181bd12008-07-27 21:46:04 +00001898 OS << "SDNode *Select_INLINEASM(SDValue N) {\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001899 << " std::vector<SDValue> Ops(N.getNode()->op_begin(), N.getNode()->op_end());\n"
Dan Gohman14a66442008-08-23 02:25:05 +00001900 << " SelectInlineAsmMemoryOperands(Ops);\n\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901
Duncan Sands92c43912008-06-06 12:08:01 +00001902 << " std::vector<MVT> VTs;\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 << " VTs.push_back(MVT::Other);\n"
1904 << " VTs.push_back(MVT::Flag);\n"
Dale Johannesen8a423f72009-02-05 22:07:54 +00001905 << " SDValue New = CurDAG->getNode(ISD::INLINEASM, N.getDebugLoc(), "
1906 "VTs, &Ops[0], Ops.size());\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001907 << " return New.getNode();\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001908 << "}\n\n";
Evan Cheng3c0eda52008-03-15 00:03:38 +00001909
Dan Gohman8181bd12008-07-27 21:46:04 +00001910 OS << "SDNode *Select_UNDEF(const SDValue &N) {\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001911 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::IMPLICIT_DEF,\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001912 << " N.getValueType());\n"
1913 << "}\n\n";
1914
Dan Gohman8181bd12008-07-27 21:46:04 +00001915 OS << "SDNode *Select_DBG_LABEL(const SDValue &N) {\n"
1916 << " SDValue Chain = N.getOperand(0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001917 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001918 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001919 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DBG_LABEL,\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001920 << " MVT::Other, Tmp, Chain);\n"
1921 << "}\n\n";
1922
Dan Gohman8181bd12008-07-27 21:46:04 +00001923 OS << "SDNode *Select_EH_LABEL(const SDValue &N) {\n"
1924 << " SDValue Chain = N.getOperand(0);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001925 << " unsigned C = cast<LabelSDNode>(N)->getLabelID();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001926 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001927 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EH_LABEL,\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001928 << " MVT::Other, Tmp, Chain);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00001929 << "}\n\n";
1930
Dan Gohman8181bd12008-07-27 21:46:04 +00001931 OS << "SDNode *Select_DECLARE(const SDValue &N) {\n"
1932 << " SDValue Chain = N.getOperand(0);\n"
1933 << " SDValue N1 = N.getOperand(1);\n"
1934 << " SDValue N2 = N.getOperand(2);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001935 << " if (!isa<FrameIndexSDNode>(N1) || !isa<GlobalAddressSDNode>(N2)) {\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001936 << " CannotYetSelect(N);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001937 << " }\n"
1938 << " int FI = cast<FrameIndexSDNode>(N1)->getIndex();\n"
1939 << " GlobalValue *GV = cast<GlobalAddressSDNode>(N2)->getGlobal();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001940 << " SDValue Tmp1 = "
Evan Cheng2e28d622008-02-02 04:07:54 +00001941 << "CurDAG->getTargetFrameIndex(FI, TLI.getPointerTy());\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001942 << " SDValue Tmp2 = "
Evan Cheng2e28d622008-02-02 04:07:54 +00001943 << "CurDAG->getTargetGlobalAddress(GV, TLI.getPointerTy());\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001944 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::DECLARE,\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001945 << " MVT::Other, Tmp1, Tmp2, Chain);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00001946 << "}\n\n";
1947
Dan Gohman8181bd12008-07-27 21:46:04 +00001948 OS << "SDNode *Select_EXTRACT_SUBREG(const SDValue &N) {\n"
1949 << " SDValue N0 = N.getOperand(0);\n"
1950 << " SDValue N1 = N.getOperand(1);\n"
Dan Gohmanfaeb4a32008-09-12 16:56:44 +00001951 << " unsigned C = cast<ConstantSDNode>(N1)->getZExtValue();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001952 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001953 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::EXTRACT_SUBREG,\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001954 << " N.getValueType(), N0, Tmp);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001955 << "}\n\n";
1956
Dan Gohman8181bd12008-07-27 21:46:04 +00001957 OS << "SDNode *Select_INSERT_SUBREG(const SDValue &N) {\n"
1958 << " SDValue N0 = N.getOperand(0);\n"
1959 << " SDValue N1 = N.getOperand(1);\n"
1960 << " SDValue N2 = N.getOperand(2);\n"
Dan Gohmanfaeb4a32008-09-12 16:56:44 +00001961 << " unsigned C = cast<ConstantSDNode>(N2)->getZExtValue();\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001962 << " SDValue Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001963 << " return CurDAG->SelectNodeTo(N.getNode(), TargetInstrInfo::INSERT_SUBREG,\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001964 << " N.getValueType(), N0, N1, Tmp);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001965 << "}\n\n";
1966
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001967 OS << "// The main instruction selector code.\n"
Dan Gohman8181bd12008-07-27 21:46:04 +00001968 << "SDNode *SelectCode(SDValue N) {\n"
Gabor Greif1c80d112008-08-28 21:40:38 +00001969 << " MVT::SimpleValueType NVT = N.getNode()->getValueType(0).getSimpleVT();\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001970 << " switch (N.getOpcode()) {\n"
Dan Gohman231412c2008-11-05 18:30:52 +00001971 << " default:\n"
1972 << " assert(!N.isMachineOpcode() && \"Node already selected!\");\n"
1973 << " break;\n"
1974 << " case ISD::EntryToken: // These nodes remain the same.\n"
Dan Gohmancc3df852008-11-05 04:14:16 +00001975 << " case ISD::MEMOPERAND:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001976 << " case ISD::BasicBlock:\n"
1977 << " case ISD::Register:\n"
1978 << " case ISD::HANDLENODE:\n"
1979 << " case ISD::TargetConstant:\n"
Nate Begemane2ba64f2008-02-14 08:57:00 +00001980 << " case ISD::TargetConstantFP:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001981 << " case ISD::TargetConstantPool:\n"
1982 << " case ISD::TargetFrameIndex:\n"
Bill Wendlingfef06052008-09-16 21:48:12 +00001983 << " case ISD::TargetExternalSymbol:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 << " case ISD::TargetJumpTable:\n"
1985 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohmancc3df852008-11-05 04:14:16 +00001986 << " case ISD::TargetGlobalAddress:\n"
1987 << " case ISD::TokenFactor:\n"
1988 << " case ISD::CopyFromReg:\n"
1989 << " case ISD::CopyToReg: {\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001990 << " return NULL;\n"
1991 << " }\n"
1992 << " case ISD::AssertSext:\n"
1993 << " case ISD::AssertZext: {\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001994 << " ReplaceUses(N, N.getOperand(0));\n"
1995 << " return NULL;\n"
1996 << " }\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001997 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001998 << " case ISD::DBG_LABEL: return Select_DBG_LABEL(N);\n"
1999 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Cheng2e28d622008-02-02 04:07:54 +00002000 << " case ISD::DECLARE: return Select_DECLARE(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00002001 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00002002 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n"
2003 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002004
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 // Loop over all of the case statements, emiting a call to each method we
2006 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00002007 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002008 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
2009 PBOI != E; ++PBOI) {
2010 const std::string &OpName = PBOI->first;
2011 // Potentially multiple versions of select for this opcode. One for each
2012 // ValueType of the node (or its first true operand if it doesn't produce a
2013 // result.
2014 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
2015 OpcodeVTMap.find(OpName);
2016 std::vector<std::string> &OpVTs = OpVTI->second;
2017 OS << " case " << OpName << ": {\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00002018 // Keep track of whether we see a pattern that has an iPtr result.
2019 bool HasPtrPattern = false;
2020 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021
Evan Chengb8b6b182007-09-04 20:18:28 +00002022 OS << " switch (NVT) {\n";
2023 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
2024 std::string &VTStr = OpVTs[i];
2025 if (VTStr.empty()) {
2026 HasDefaultPattern = true;
2027 continue;
2028 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002029
Evan Chengb8b6b182007-09-04 20:18:28 +00002030 // If this is a match on iPTR: don't emit it directly, we need special
2031 // code.
2032 if (VTStr == "_iPTR") {
2033 HasPtrPattern = true;
2034 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002035 }
Evan Chengb8b6b182007-09-04 20:18:28 +00002036 OS << " case MVT::" << VTStr.substr(1) << ":\n"
2037 << " return Select_" << getLegalCName(OpName)
2038 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002039 }
Evan Chengb8b6b182007-09-04 20:18:28 +00002040 OS << " default:\n";
2041
2042 // If there is an iPTR result version of this pattern, emit it here.
2043 if (HasPtrPattern) {
Duncan Sands92c43912008-06-06 12:08:01 +00002044 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00002045 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
2046 }
2047 if (HasDefaultPattern) {
2048 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
2049 }
2050 OS << " break;\n";
2051 OS << " }\n";
2052 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053 OS << " }\n";
2054 }
2055
2056 OS << " } // end of big switch.\n\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002057 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
2058 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
2059 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00002060 << " CannotYetSelect(N);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002061 << " } else {\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00002062 << " CannotYetSelectIntrinsic(N);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002063 << " }\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00002064 << " return NULL;\n"
2065 << "}\n\n";
2066
2067 OS << "void CannotYetSelect(SDValue N) DISABLE_INLINE {\n"
2068 << " cerr << \"Cannot yet select: \";\n"
2069 << " N.getNode()->dump(CurDAG);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002070 << " cerr << '\\n';\n"
2071 << " abort();\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00002072 << "}\n\n";
2073
2074 OS << "void CannotYetSelectIntrinsic(SDValue N) DISABLE_INLINE {\n"
2075 << " cerr << \"Cannot yet select: \";\n"
2076 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
2077 << "N.getOperand(0).getValueType() == MVT::Other))->getZExtValue();\n"
2078 << " cerr << \"intrinsic %\"<< "
2079 << "Intrinsic::getName((Intrinsic::ID)iid);\n"
2080 << " cerr << '\\n';\n"
2081 << " abort();\n"
2082 << "}\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002083}
2084
2085void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00002086 EmitSourceFileHeader("DAG Instruction Selector for the " +
2087 CGP.getTargetInfo().getName() + " target", OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088
2089 OS << "// *** NOTE: This file is #included into the middle of the target\n"
2090 << "// *** instruction selector class. These functions are really "
2091 << "methods.\n\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00002092
Roman Levenstein393ad0f2008-05-14 10:17:11 +00002093 OS << "// Include standard, target-independent definitions and methods used\n"
2094 << "// by the instruction selector.\n";
2095 OS << "#include <llvm/CodeGen/DAGISelHeader.h>\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002096
Chris Lattner227da452008-01-05 22:54:53 +00002097 EmitNodeTransforms(OS);
Chris Lattner7fdd9342008-01-05 22:43:57 +00002098 EmitPredicateFunctions(OS);
2099
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerae506702008-01-06 01:10:31 +00002101 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00002102 I != E; ++I) {
2103 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2104 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002105 DOUT << "\n";
2106 }
2107
2108 // At this point, we have full information about the 'Patterns' we need to
2109 // parse, both implicitly from instructions as well as from explicit pattern
2110 // definitions. Emit the resultant instruction selector.
2111 EmitInstructionSelector(OS);
2112
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002113}