blob: 1f568ad5ee6738522a14f9be42ae6f81b2a7ea3b [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"
17#include "llvm/Support/Debug.h"
18#include "llvm/Support/MathExtras.h"
19#include "llvm/Support/Streams.h"
20#include <algorithm>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000021using namespace llvm;
22
23//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +000024// DAGISelEmitter Helper methods
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025//
26
Chris Lattner4ca8ff02008-01-05 22:25:12 +000027/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
28/// ComplexPattern.
29static bool NodeIsComplexPattern(TreePatternNode *N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030 return (N->isLeaf() &&
31 dynamic_cast<DefInit*>(N->getLeafValue()) &&
32 static_cast<DefInit*>(N->getLeafValue())->getDef()->
33 isSubClassOf("ComplexPattern"));
34}
35
Chris Lattner4ca8ff02008-01-05 22:25:12 +000036/// NodeGetComplexPattern - return the pointer to the ComplexPattern if N
37/// is a leaf node and a subclass of ComplexPattern, else it returns NULL.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000038static const ComplexPattern *NodeGetComplexPattern(TreePatternNode *N,
Chris Lattnerae506702008-01-06 01:10:31 +000039 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040 if (N->isLeaf() &&
41 dynamic_cast<DefInit*>(N->getLeafValue()) &&
42 static_cast<DefInit*>(N->getLeafValue())->getDef()->
43 isSubClassOf("ComplexPattern")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +000044 return &CGP.getComplexPattern(static_cast<DefInit*>(N->getLeafValue())
45 ->getDef());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000046 }
47 return NULL;
48}
49
50/// getPatternSize - Return the 'size' of this pattern. We want to match large
51/// patterns before small ones. This is used to determine the size of a
52/// pattern.
Chris Lattnerae506702008-01-06 01:10:31 +000053static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +000054 assert((MVT::isExtIntegerInVTs(P->getExtTypes()) ||
55 MVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000056 P->getExtTypeNum(0) == MVT::isVoid ||
57 P->getExtTypeNum(0) == MVT::Flag ||
58 P->getExtTypeNum(0) == MVT::iPTR) &&
59 "Not a valid pattern node to size!");
60 unsigned Size = 3; // The node itself.
61 // If the root node is a ConstantSDNode, increases its size.
62 // e.g. (set R32:$dst, 0).
63 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
64 Size += 2;
65
66 // FIXME: This is a hack to statically increase the priority of patterns
67 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
68 // Later we can allow complexity / cost for each pattern to be (optionally)
69 // specified. To get best possible pattern match we'll need to dynamically
70 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner4ca8ff02008-01-05 22:25:12 +000071 const ComplexPattern *AM = NodeGetComplexPattern(P, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000072 if (AM)
73 Size += AM->getNumOperands() * 3;
74
75 // If this node has some predicate function that must match, it adds to the
76 // complexity of this node.
77 if (!P->getPredicateFn().empty())
78 ++Size;
79
80 // Count children in the count if they are also nodes.
81 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
82 TreePatternNode *Child = P->getChild(i);
83 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner4ca8ff02008-01-05 22:25:12 +000084 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000085 else if (Child->isLeaf()) {
86 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
87 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
88 else if (NodeIsComplexPattern(Child))
Chris Lattner4ca8ff02008-01-05 22:25:12 +000089 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000090 else if (!Child->getPredicateFn().empty())
91 ++Size;
92 }
93 }
94
95 return Size;
96}
97
98/// getResultPatternCost - Compute the number of instructions for this pattern.
99/// This is a temporary hack. We should really include the instruction
100/// latencies in this calculation.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000101static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000102 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000103 if (P->isLeaf()) return 0;
104
105 unsigned Cost = 0;
106 Record *Op = P->getOperator();
107 if (Op->isSubClassOf("Instruction")) {
108 Cost++;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000109 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000110 if (II.usesCustomDAGSchedInserter)
111 Cost += 10;
112 }
113 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000114 Cost += getResultPatternCost(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000115 return Cost;
116}
117
118/// getResultPatternCodeSize - Compute the code size of instructions for this
119/// pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000120static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000121 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 if (P->isLeaf()) return 0;
123
124 unsigned Cost = 0;
125 Record *Op = P->getOperator();
126 if (Op->isSubClassOf("Instruction")) {
127 Cost += Op->getValueAsInt("CodeSize");
128 }
129 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000130 Cost += getResultPatternSize(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 return Cost;
132}
133
134// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
135// In particular, we want to match maximal patterns first and lowest cost within
136// a particular complexity first.
137struct PatternSortingPredicate {
Chris Lattnerae506702008-01-06 01:10:31 +0000138 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
139 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000140
Chris Lattner81915752008-01-05 22:30:17 +0000141 bool operator()(const PatternToMatch *LHS,
142 const PatternToMatch *RHS) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000143 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
144 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 LHSSize += LHS->getAddedComplexity();
146 RHSSize += RHS->getAddedComplexity();
147 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
148 if (LHSSize < RHSSize) return false;
149
150 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000151 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
152 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000153 if (LHSCost < RHSCost) return true;
154 if (LHSCost > RHSCost) return false;
155
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000156 return getResultPatternSize(LHS->getDstPattern(), CGP) <
157 getResultPatternSize(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000158 }
159};
160
161/// getRegisterValueType - Look up and return the first ValueType of specified
162/// RegisterClass record
163static MVT::ValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
164 if (const CodeGenRegisterClass *RC = T.getRegisterClassForRegister(R))
165 return RC->getValueTypeNum(0);
166 return MVT::Other;
167}
168
169
170/// RemoveAllTypes - A quick recursive walk over a pattern which removes all
171/// type information from it.
172static void RemoveAllTypes(TreePatternNode *N) {
173 N->removeTypes();
174 if (!N->isLeaf())
175 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
176 RemoveAllTypes(N->getChild(i));
177}
178
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179/// NodeHasProperty - return true if TreePatternNode has the specified
180/// property.
181static bool NodeHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000182 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 if (N->isLeaf()) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000184 const ComplexPattern *CP = NodeGetComplexPattern(N, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000185 if (CP)
186 return CP->hasProperty(Property);
187 return false;
188 }
189 Record *Operator = N->getOperator();
190 if (!Operator->isSubClassOf("SDNode")) return false;
191
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000192 return CGP.getSDNodeInfo(Operator).hasProperty(Property);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000193}
194
195static bool PatternHasProperty(TreePatternNode *N, SDNP Property,
Chris Lattnerae506702008-01-06 01:10:31 +0000196 CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000197 if (NodeHasProperty(N, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000198 return true;
199
200 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
201 TreePatternNode *Child = N->getChild(i);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000202 if (PatternHasProperty(Child, Property, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 return true;
204 }
205
206 return false;
207}
208
Chris Lattner7fdd9342008-01-05 22:43:57 +0000209//===----------------------------------------------------------------------===//
Chris Lattner227da452008-01-05 22:54:53 +0000210// Node Transformation emitter implementation.
211//
212void DAGISelEmitter::EmitNodeTransforms(std::ostream &OS) {
213 // Walk the pattern fragments, adding them to a map, which sorts them by
214 // name.
Chris Lattnerae506702008-01-06 01:10:31 +0000215 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner227da452008-01-05 22:54:53 +0000216 NXsByNameTy NXsByName;
217
Chris Lattnerae506702008-01-06 01:10:31 +0000218 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner227da452008-01-05 22:54:53 +0000219 I != E; ++I)
220 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
221
222 OS << "\n// Node transformations.\n";
223
224 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
225 I != E; ++I) {
226 Record *SDNode = I->second.first;
227 std::string Code = I->second.second;
228
229 if (Code.empty()) continue; // Empty code? Skip it.
230
Chris Lattner14948ea2008-01-05 22:58:54 +0000231 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner227da452008-01-05 22:54:53 +0000232 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
233
234 OS << "inline SDOperand Transform_" << I->first << "(SDNode *" << C2
235 << ") {\n";
236 if (ClassName != "SDNode")
237 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
238 OS << Code << "\n}\n";
239 }
240}
241
242//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +0000243// Predicate emitter implementation.
244//
245
246void DAGISelEmitter::EmitPredicateFunctions(std::ostream &OS) {
247 OS << "\n// Predicate functions.\n";
248
249 // Walk the pattern fragments, adding them to a map, which sorts them by
250 // name.
251 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
252 PFsByNameTy PFsByName;
253
Chris Lattnerae506702008-01-06 01:10:31 +0000254 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000255 I != E; ++I)
256 PFsByName.insert(std::make_pair(I->first->getName(), *I));
257
258
259 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
260 I != E; ++I) {
261 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
262 TreePattern *P = I->second.second;
263
264 // If there is a code init for this fragment, emit the predicate code.
265 std::string Code = PatFragRecord->getValueAsCode("Predicate");
266 if (Code.empty()) continue;
267
268 if (P->getOnlyTree()->isLeaf())
269 OS << "inline bool Predicate_" << PatFragRecord->getName()
270 << "(SDNode *N) {\n";
271 else {
272 std::string ClassName =
Chris Lattner14948ea2008-01-05 22:58:54 +0000273 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000274 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
275
276 OS << "inline bool Predicate_" << PatFragRecord->getName()
277 << "(SDNode *" << C2 << ") {\n";
278 if (ClassName != "SDNode")
279 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
280 }
281 OS << Code << "\n}\n";
282 }
283
284 OS << "\n\n";
285}
286
287
288//===----------------------------------------------------------------------===//
289// PatternCodeEmitter implementation.
290//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000291class PatternCodeEmitter {
292private:
Chris Lattnerae506702008-01-06 01:10:31 +0000293 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294
295 // Predicates.
296 ListInit *Predicates;
297 // Pattern cost.
298 unsigned Cost;
299 // Instruction selector pattern.
300 TreePatternNode *Pattern;
301 // Matched instruction.
302 TreePatternNode *Instruction;
303
304 // Node to name mapping
305 std::map<std::string, std::string> VariableMap;
306 // Node to operator mapping
307 std::map<std::string, Record*> OperatorMap;
308 // Names of all the folded nodes which produce chains.
309 std::vector<std::pair<std::string, unsigned> > FoldedChains;
310 // Original input chain(s).
311 std::vector<std::pair<std::string, std::string> > OrigChains;
312 std::set<std::string> Duplicates;
313
Dan Gohmanf14b4472008-01-31 00:25:39 +0000314 /// LSI - Load/Store information.
315 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
316 /// for each memory access. This facilitates the use of AliasAnalysis in
317 /// the backend.
318 std::vector<std::string> LSI;
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 /// GeneratedCode - This is the buffer that we emit code to. The first int
321 /// indicates whether this is an exit predicate (something that should be
322 /// tested, and if true, the match fails) [when 1], or normal code to emit
323 /// [when 0], or initialization code to emit [when 2].
324 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
325 /// GeneratedDecl - This is the set of all SDOperand declarations needed for
326 /// the set of patterns for each top-level opcode.
327 std::set<std::string> &GeneratedDecl;
328 /// TargetOpcodes - The target specific opcodes used by the resulting
329 /// instructions.
330 std::vector<std::string> &TargetOpcodes;
331 std::vector<std::string> &TargetVTs;
332
333 std::string ChainName;
334 unsigned TmpNo;
335 unsigned OpcNo;
336 unsigned VTNo;
337
338 void emitCheck(const std::string &S) {
339 if (!S.empty())
340 GeneratedCode.push_back(std::make_pair(1, S));
341 }
342 void emitCode(const std::string &S) {
343 if (!S.empty())
344 GeneratedCode.push_back(std::make_pair(0, S));
345 }
346 void emitInit(const std::string &S) {
347 if (!S.empty())
348 GeneratedCode.push_back(std::make_pair(2, S));
349 }
350 void emitDecl(const std::string &S) {
351 assert(!S.empty() && "Invalid declaration");
352 GeneratedDecl.insert(S);
353 }
354 void emitOpcode(const std::string &Opc) {
355 TargetOpcodes.push_back(Opc);
356 OpcNo++;
357 }
358 void emitVT(const std::string &VT) {
359 TargetVTs.push_back(VT);
360 VTNo++;
361 }
362public:
Chris Lattnerae506702008-01-06 01:10:31 +0000363 PatternCodeEmitter(CodeGenDAGPatterns &cgp, ListInit *preds,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000364 TreePatternNode *pattern, TreePatternNode *instr,
365 std::vector<std::pair<unsigned, std::string> > &gc,
366 std::set<std::string> &gd,
367 std::vector<std::string> &to,
368 std::vector<std::string> &tv)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000369 : CGP(cgp), Predicates(preds), Pattern(pattern), Instruction(instr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000370 GeneratedCode(gc), GeneratedDecl(gd),
371 TargetOpcodes(to), TargetVTs(tv),
372 TmpNo(0), OpcNo(0), VTNo(0) {}
373
374 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
375 /// if the match fails. At this point, we already know that the opcode for N
376 /// matches, and the SDNode for the result has the RootName specified name.
377 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
378 const std::string &RootName, const std::string &ChainSuffix,
379 bool &FoundChain) {
Dan Gohmanf14b4472008-01-31 00:25:39 +0000380
381 // Save loads/stores matched by a pattern.
382 if (!N->isLeaf() && N->getName().empty() &&
383 ((N->getOperator()->getName() == "ld") ||
384 (N->getOperator()->getName() == "st") ||
385 (N->getOperator()->getName() == "ist"))) {
386 LSI.push_back(RootName);
387 }
388
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 bool isRoot = (P == NULL);
390 // Emit instruction predicates. Each predicate is just a string for now.
391 if (isRoot) {
392 std::string PredicateCheck;
393 for (unsigned i = 0, e = Predicates->getSize(); i != e; ++i) {
394 if (DefInit *Pred = dynamic_cast<DefInit*>(Predicates->getElement(i))) {
395 Record *Def = Pred->getDef();
396 if (!Def->isSubClassOf("Predicate")) {
397#ifndef NDEBUG
398 Def->dump();
399#endif
400 assert(0 && "Unknown predicate type!");
401 }
402 if (!PredicateCheck.empty())
403 PredicateCheck += " && ";
404 PredicateCheck += "(" + Def->getValueAsString("CondString") + ")";
405 }
406 }
407
408 emitCheck(PredicateCheck);
409 }
410
411 if (N->isLeaf()) {
412 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
413 emitCheck("cast<ConstantSDNode>(" + RootName +
414 ")->getSignExtended() == " + itostr(II->getValue()));
415 return;
416 } else if (!NodeIsComplexPattern(N)) {
417 assert(0 && "Cannot match this as a leaf value!");
418 abort();
419 }
420 }
421
422 // If this node has a name associated with it, capture it in VariableMap. If
423 // we already saw this in the pattern, emit code to verify dagness.
424 if (!N->getName().empty()) {
425 std::string &VarMapEntry = VariableMap[N->getName()];
426 if (VarMapEntry.empty()) {
427 VarMapEntry = RootName;
428 } else {
429 // If we get here, this is a second reference to a specific name. Since
430 // we already have checked that the first reference is valid, we don't
431 // have to recursively match it, just check that it's the same as the
432 // previously named thing.
433 emitCheck(VarMapEntry + " == " + RootName);
434 return;
435 }
436
437 if (!N->isLeaf())
438 OperatorMap[N->getName()] = N->getOperator();
439 }
440
441
442 // Emit code to load the child nodes and match their contents recursively.
443 unsigned OpNo = 0;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000444 bool NodeHasChain = NodeHasProperty (N, SDNPHasChain, CGP);
445 bool HasChain = PatternHasProperty(N, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000446 bool EmittedUseCheck = false;
447 if (HasChain) {
448 if (NodeHasChain)
449 OpNo = 1;
450 if (!isRoot) {
451 // Multiple uses of actual result?
452 emitCheck(RootName + ".hasOneUse()");
453 EmittedUseCheck = true;
454 if (NodeHasChain) {
455 // If the immediate use can somehow reach this node through another
456 // path, then can't fold it either or it will create a cycle.
457 // e.g. In the following diagram, XX can reach ld through YY. If
458 // ld is folded into XX, then YY is both a predecessor and a successor
459 // of XX.
460 //
461 // [ld]
462 // ^ ^
463 // | |
464 // / \---
465 // / [YY]
466 // | ^
467 // [XX]-------|
468 bool NeedCheck = false;
469 if (P != Pattern)
470 NeedCheck = true;
471 else {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000472 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 NeedCheck =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000474 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
475 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
476 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000477 PInfo.getNumOperands() > 1 ||
478 PInfo.hasProperty(SDNPHasChain) ||
479 PInfo.hasProperty(SDNPInFlag) ||
480 PInfo.hasProperty(SDNPOptInFlag);
481 }
482
483 if (NeedCheck) {
484 std::string ParentName(RootName.begin(), RootName.end()-1);
485 emitCheck("CanBeFoldedBy(" + RootName + ".Val, " + ParentName +
486 ".Val, N.Val)");
487 }
488 }
489 }
490
491 if (NodeHasChain) {
492 if (FoundChain) {
493 emitCheck("(" + ChainName + ".Val == " + RootName + ".Val || "
494 "IsChainCompatible(" + ChainName + ".Val, " +
495 RootName + ".Val))");
496 OrigChains.push_back(std::make_pair(ChainName, RootName));
497 } else
498 FoundChain = true;
499 ChainName = "Chain" + ChainSuffix;
500 emitInit("SDOperand " + ChainName + " = " + RootName +
501 ".getOperand(0);");
502 }
503 }
504
505 // Don't fold any node which reads or writes a flag and has multiple uses.
506 // FIXME: We really need to separate the concepts of flag and "glue". Those
507 // real flag results, e.g. X86CMP output, can have multiple uses.
508 // FIXME: If the optional incoming flag does not exist. Then it is ok to
509 // fold it.
510 if (!isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000511 (PatternHasProperty(N, SDNPInFlag, CGP) ||
512 PatternHasProperty(N, SDNPOptInFlag, CGP) ||
513 PatternHasProperty(N, SDNPOutFlag, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000514 if (!EmittedUseCheck) {
515 // Multiple uses of actual result?
516 emitCheck(RootName + ".hasOneUse()");
517 }
518 }
519
520 // If there is a node predicate for this, emit the call.
521 if (!N->getPredicateFn().empty())
522 emitCheck(N->getPredicateFn() + "(" + RootName + ".Val)");
523
524
525 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
526 // a constant without a predicate fn that has more that one bit set, handle
527 // this as a special case. This is usually for targets that have special
528 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
529 // handling stuff). Using these instructions is often far more efficient
530 // than materializing the constant. Unfortunately, both the instcombiner
531 // and the dag combiner can often infer that bits are dead, and thus drop
532 // them from the mask in the dag. For example, it might turn 'AND X, 255'
533 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
534 // to handle this.
535 if (!N->isLeaf() &&
536 (N->getOperator()->getName() == "and" ||
537 N->getOperator()->getName() == "or") &&
538 N->getChild(1)->isLeaf() &&
539 N->getChild(1)->getPredicateFn().empty()) {
540 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
541 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
542 emitInit("SDOperand " + RootName + "0" + " = " +
543 RootName + ".getOperand(" + utostr(0) + ");");
544 emitInit("SDOperand " + RootName + "1" + " = " +
545 RootName + ".getOperand(" + utostr(1) + ");");
546
547 emitCheck("isa<ConstantSDNode>(" + RootName + "1)");
548 const char *MaskPredicate = N->getOperator()->getName() == "or"
549 ? "CheckOrMask(" : "CheckAndMask(";
550 emitCheck(MaskPredicate + RootName + "0, cast<ConstantSDNode>(" +
551 RootName + "1), " + itostr(II->getValue()) + ")");
552
Christopher Lamb059c7c92008-01-31 07:27:46 +0000553 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000554 ChainSuffix + utostr(0), FoundChain);
555 return;
556 }
557 }
558 }
559
560 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
561 emitInit("SDOperand " + RootName + utostr(OpNo) + " = " +
562 RootName + ".getOperand(" +utostr(OpNo) + ");");
563
Christopher Lamb059c7c92008-01-31 07:27:46 +0000564 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo), RootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000565 ChainSuffix + utostr(OpNo), FoundChain);
566 }
567
568 // Handle cases when root is a complex pattern.
569 const ComplexPattern *CP;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000570 if (isRoot && N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000571 std::string Fn = CP->getSelectFunc();
572 unsigned NumOps = CP->getNumOperands();
573 for (unsigned i = 0; i < NumOps; ++i) {
574 emitDecl("CPTmp" + utostr(i));
575 emitCode("SDOperand CPTmp" + utostr(i) + ";");
576 }
577 if (CP->hasProperty(SDNPHasChain)) {
578 emitDecl("CPInChain");
579 emitDecl("Chain" + ChainSuffix);
580 emitCode("SDOperand CPInChain;");
581 emitCode("SDOperand Chain" + ChainSuffix + ";");
582 }
583
584 std::string Code = Fn + "(" + RootName + ", " + RootName;
585 for (unsigned i = 0; i < NumOps; i++)
586 Code += ", CPTmp" + utostr(i);
587 if (CP->hasProperty(SDNPHasChain)) {
588 ChainName = "Chain" + ChainSuffix;
589 Code += ", CPInChain, Chain" + ChainSuffix;
590 }
591 emitCheck(Code + ")");
592 }
593 }
594
595 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb059c7c92008-01-31 07:27:46 +0000596 const std::string &RootName,
597 const std::string &ParentRootName,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000598 const std::string &ChainSuffix, bool &FoundChain) {
599 if (!Child->isLeaf()) {
600 // If it's not a leaf, recursively match.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000601 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000602 emitCheck(RootName + ".getOpcode() == " +
603 CInfo.getEnumName());
604 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000605 if (NodeHasProperty(Child, SDNPHasChain, CGP))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606 FoldedChains.push_back(std::make_pair(RootName, CInfo.getNumResults()));
607 } else {
608 // If this child has a name associated with it, capture it in VarMap. If
609 // we already saw this in the pattern, emit code to verify dagness.
610 if (!Child->getName().empty()) {
611 std::string &VarMapEntry = VariableMap[Child->getName()];
612 if (VarMapEntry.empty()) {
613 VarMapEntry = RootName;
614 } else {
615 // If we get here, this is a second reference to a specific name.
616 // Since we already have checked that the first reference is valid,
617 // we don't have to recursively match it, just check that it's the
618 // same as the previously named thing.
619 emitCheck(VarMapEntry + " == " + RootName);
620 Duplicates.insert(RootName);
621 return;
622 }
623 }
624
625 // Handle leaves of various types.
626 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
627 Record *LeafRec = DI->getDef();
628 if (LeafRec->isSubClassOf("RegisterClass") ||
629 LeafRec->getName() == "ptr_rc") {
630 // Handle register references. Nothing to do here.
631 } else if (LeafRec->isSubClassOf("Register")) {
632 // Handle register references.
633 } else if (LeafRec->isSubClassOf("ComplexPattern")) {
634 // Handle complex pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000635 const ComplexPattern *CP = NodeGetComplexPattern(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000636 std::string Fn = CP->getSelectFunc();
637 unsigned NumOps = CP->getNumOperands();
638 for (unsigned i = 0; i < NumOps; ++i) {
639 emitDecl("CPTmp" + utostr(i));
640 emitCode("SDOperand CPTmp" + utostr(i) + ";");
641 }
642 if (CP->hasProperty(SDNPHasChain)) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000643 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 FoldedChains.push_back(std::make_pair("CPInChain",
645 PInfo.getNumResults()));
646 ChainName = "Chain" + ChainSuffix;
647 emitDecl("CPInChain");
648 emitDecl(ChainName);
649 emitCode("SDOperand CPInChain;");
650 emitCode("SDOperand " + ChainName + ";");
651 }
652
Christopher Lamb059c7c92008-01-31 07:27:46 +0000653 std::string Code = Fn + "(";
654 if (CP->hasAttribute(CPAttrParentAsRoot)) {
655 Code += ParentRootName + ", ";
656 } else {
657 Code += "N, ";
658 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000659 if (CP->hasProperty(SDNPHasChain)) {
660 std::string ParentName(RootName.begin(), RootName.end()-1);
661 Code += ParentName + ", ";
662 }
663 Code += RootName;
664 for (unsigned i = 0; i < NumOps; i++)
665 Code += ", CPTmp" + utostr(i);
666 if (CP->hasProperty(SDNPHasChain))
667 Code += ", CPInChain, Chain" + ChainSuffix;
668 emitCheck(Code + ")");
669 } else if (LeafRec->getName() == "srcvalue") {
670 // Place holder for SRCVALUE nodes. Nothing to do here.
671 } else if (LeafRec->isSubClassOf("ValueType")) {
672 // Make sure this is the specified value type.
673 emitCheck("cast<VTSDNode>(" + RootName +
674 ")->getVT() == MVT::" + LeafRec->getName());
675 } else if (LeafRec->isSubClassOf("CondCode")) {
676 // Make sure this is the specified cond code.
677 emitCheck("cast<CondCodeSDNode>(" + RootName +
678 ")->get() == ISD::" + LeafRec->getName());
679 } else {
680#ifndef NDEBUG
681 Child->dump();
682 cerr << " ";
683#endif
684 assert(0 && "Unknown leaf type!");
685 }
686
687 // If there is a node predicate for this, emit the call.
688 if (!Child->getPredicateFn().empty())
689 emitCheck(Child->getPredicateFn() + "(" + RootName +
690 ".Val)");
691 } else if (IntInit *II =
692 dynamic_cast<IntInit*>(Child->getLeafValue())) {
693 emitCheck("isa<ConstantSDNode>(" + RootName + ")");
694 unsigned CTmp = TmpNo++;
695 emitCode("int64_t CN"+utostr(CTmp)+" = cast<ConstantSDNode>("+
696 RootName + ")->getSignExtended();");
697
698 emitCheck("CN" + utostr(CTmp) + " == " +itostr(II->getValue()));
699 } else {
700#ifndef NDEBUG
701 Child->dump();
702#endif
703 assert(0 && "Unknown leaf type!");
704 }
705 }
706 }
707
708 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
709 /// we actually have to build a DAG!
710 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000711 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712 bool InFlagDecled, bool ResNodeDecled,
713 bool LikeLeaf = false, bool isRoot = false) {
714 // List of arguments of getTargetNode() or SelectNodeTo().
715 std::vector<std::string> NodeOps;
716 // This is something selected from the pattern we matched.
717 if (!N->getName().empty()) {
Scott Michel30124c22008-01-29 02:29:31 +0000718 const std::string &VarName = N->getName();
719 std::string Val = VariableMap[VarName];
720 bool ModifiedVal = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000721 assert(!Val.empty() &&
722 "Variable referenced but not defined and not caught earlier!");
723 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
724 // Already selected this operand, just return the tmpval.
725 NodeOps.push_back(Val);
726 return NodeOps;
727 }
728
729 const ComplexPattern *CP;
730 unsigned ResNo = TmpNo++;
731 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
732 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
733 std::string CastType;
Scott Michel30124c22008-01-29 02:29:31 +0000734 std::string TmpVar = "Tmp" + utostr(ResNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 switch (N->getTypeNum(0)) {
736 default:
737 cerr << "Cannot handle " << getEnumName(N->getTypeNum(0))
738 << " type as an immediate constant. Aborting\n";
739 abort();
740 case MVT::i1: CastType = "bool"; break;
741 case MVT::i8: CastType = "unsigned char"; break;
742 case MVT::i16: CastType = "unsigned short"; break;
743 case MVT::i32: CastType = "unsigned"; break;
744 case MVT::i64: CastType = "uint64_t"; break;
745 }
Scott Michel30124c22008-01-29 02:29:31 +0000746 emitCode("SDOperand " + TmpVar +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000747 " = CurDAG->getTargetConstant(((" + CastType +
748 ") cast<ConstantSDNode>(" + Val + ")->getValue()), " +
749 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000750 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
751 // value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000752 Val = TmpVar;
753 ModifiedVal = true;
754 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000755 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
756 Record *Op = OperatorMap[N->getName()];
757 // Transform ExternalSymbol to TargetExternalSymbol
758 if (Op && Op->getName() == "externalsym") {
Scott Michel30124c22008-01-29 02:29:31 +0000759 std::string TmpVar = "Tmp"+utostr(ResNo);
760 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000761 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
762 Val + ")->getSymbol(), " +
763 getEnumName(N->getTypeNum(0)) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
765 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000766 Val = TmpVar;
767 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000768 }
Scott Michel30124c22008-01-29 02:29:31 +0000769 NodeOps.push_back(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000770 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
771 || N->getOperator()->getName() == "tglobaltlsaddr")) {
772 Record *Op = OperatorMap[N->getName()];
773 // Transform GlobalAddress to TargetGlobalAddress
774 if (Op && (Op->getName() == "globaladdr" ||
775 Op->getName() == "globaltlsaddr")) {
Scott Michel30124c22008-01-29 02:29:31 +0000776 std::string TmpVar = "Tmp" + utostr(ResNo);
777 emitCode("SDOperand " + TmpVar + " = CurDAG->getTarget"
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000778 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
779 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
780 ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
782 // this value if used multiple times by this pattern result.
Scott Michel30124c22008-01-29 02:29:31 +0000783 Val = TmpVar;
784 ModifiedVal = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000786 NodeOps.push_back(Val);
Scott Michel30124c22008-01-29 02:29:31 +0000787 } else if (!N->isLeaf()
788 && (N->getOperator()->getName() == "texternalsym"
789 || N->getOperator()->getName() == "tconstpool")) {
790 // Do not rewrite the variable name, since we don't generate a new
791 // temporary.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000792 NodeOps.push_back(Val);
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000793 } else if (N->isLeaf() && (CP = NodeGetComplexPattern(N, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000794 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
795 emitCode("AddToISelQueue(CPTmp" + utostr(i) + ");");
796 NodeOps.push_back("CPTmp" + utostr(i));
797 }
798 } else {
799 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
800 // node even if it isn't one. Don't select it.
801 if (!LikeLeaf) {
802 emitCode("AddToISelQueue(" + Val + ");");
803 if (isRoot && N->isLeaf()) {
804 emitCode("ReplaceUses(N, " + Val + ");");
805 emitCode("return NULL;");
806 }
807 }
808 NodeOps.push_back(Val);
809 }
Scott Michel30124c22008-01-29 02:29:31 +0000810
811 if (ModifiedVal) {
812 VariableMap[VarName] = Val;
813 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000814 return NodeOps;
815 }
816 if (N->isLeaf()) {
817 // If this is an explicit register reference, handle it.
818 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
819 unsigned ResNo = TmpNo++;
820 if (DI->getDef()->isSubClassOf("Register")) {
821 emitCode("SDOperand Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000822 getQualifiedName(DI->getDef()) + ", " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000823 getEnumName(N->getTypeNum(0)) + ");");
824 NodeOps.push_back("Tmp" + utostr(ResNo));
825 return NodeOps;
826 } else if (DI->getDef()->getName() == "zero_reg") {
827 emitCode("SDOperand Tmp" + utostr(ResNo) +
828 " = CurDAG->getRegister(0, " +
829 getEnumName(N->getTypeNum(0)) + ");");
830 NodeOps.push_back("Tmp" + utostr(ResNo));
831 return NodeOps;
832 }
833 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
834 unsigned ResNo = TmpNo++;
835 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
836 emitCode("SDOperand Tmp" + utostr(ResNo) +
837 " = CurDAG->getTargetConstant(" + itostr(II->getValue()) +
838 ", " + getEnumName(N->getTypeNum(0)) + ");");
839 NodeOps.push_back("Tmp" + utostr(ResNo));
840 return NodeOps;
841 }
842
843#ifndef NDEBUG
844 N->dump();
845#endif
846 assert(0 && "Unknown leaf type!");
847 return NodeOps;
848 }
849
850 Record *Op = N->getOperator();
851 if (Op->isSubClassOf("Instruction")) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000852 const CodeGenTarget &CGT = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000853 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000854 const DAGInstruction &Inst = CGP.getInstruction(Op);
Chris Lattner7c6e5852008-01-06 01:52:22 +0000855 const TreePattern *InstPat = Inst.getPattern();
Evan Chengf031fcb2007-09-25 01:48:59 +0000856 // FIXME: Assume actual pattern comes before "implicit".
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000857 TreePatternNode *InstPatNode =
Evan Cheng775baac2007-09-12 23:30:14 +0000858 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
859 : (InstPat ? InstPat->getTree(0) : NULL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000860 if (InstPatNode && InstPatNode->getOperator()->getName() == "set") {
Evan Chengf37df842007-09-11 19:52:18 +0000861 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 }
Chris Lattner2fb37c02008-01-07 05:19:29 +0000863 bool HasVarOps = isRoot && II.isVariadic;
Evan Cheng775baac2007-09-12 23:30:14 +0000864 // FIXME: fix how we deal with physical register operands.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
Evan Cheng775baac2007-09-12 23:30:14 +0000866 bool HasImpResults = isRoot && DstRegs.size() > 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867 bool NodeHasOptInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000868 PatternHasProperty(Pattern, SDNPOptInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000869 bool NodeHasInFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000870 PatternHasProperty(Pattern, SDNPInFlag, CGP);
Evan Chengdec1dd12007-09-07 23:59:02 +0000871 bool NodeHasOutFlag = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000872 PatternHasProperty(Pattern, SDNPOutFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000873 bool NodeHasChain = InstPatNode &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000874 PatternHasProperty(InstPatNode, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 bool InputHasChain = isRoot &&
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000876 NodeHasProperty(Pattern, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000877 unsigned NumResults = Inst.getNumResults();
Evan Cheng775baac2007-09-12 23:30:14 +0000878 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000879
880 if (NodeHasOptInFlag) {
881 emitCode("bool HasInFlag = "
882 "(N.getOperand(N.getNumOperands()-1).getValueType() == MVT::Flag);");
883 }
884 if (HasVarOps)
885 emitCode("SmallVector<SDOperand, 8> Ops" + utostr(OpcNo) + ";");
886
887 // How many results is this pattern expected to produce?
Evan Cheng775baac2007-09-12 23:30:14 +0000888 unsigned NumPatResults = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000889 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
890 MVT::ValueType VT = Pattern->getTypeNum(i);
891 if (VT != MVT::isVoid && VT != MVT::Flag)
Evan Cheng775baac2007-09-12 23:30:14 +0000892 NumPatResults++;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000893 }
894
895 if (OrigChains.size() > 0) {
896 // The original input chain is being ignored. If it is not just
897 // pointing to the op that's being folded, we should create a
898 // TokenFactor with it and the chain of the folded op as the new chain.
899 // We could potentially be doing multiple levels of folding, in that
900 // case, the TokenFactor can have more operands.
901 emitCode("SmallVector<SDOperand, 8> InChains;");
902 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
903 emitCode("if (" + OrigChains[i].first + ".Val != " +
904 OrigChains[i].second + ".Val) {");
905 emitCode(" AddToISelQueue(" + OrigChains[i].first + ");");
906 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
907 emitCode("}");
908 }
909 emitCode("AddToISelQueue(" + ChainName + ");");
910 emitCode("InChains.push_back(" + ChainName + ");");
911 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, MVT::Other, "
912 "&InChains[0], InChains.size());");
913 }
914
915 // Loop over all of the operands of the instruction pattern, emitting code
916 // to fill them all in. The node 'N' usually has number children equal to
917 // the number of input operands of the instruction. However, in cases
918 // where there are predicate operands for an instruction, we need to fill
919 // in the 'execute always' values. Match up the node operands to the
920 // instruction operands to do this.
921 std::vector<std::string> AllOps;
922 unsigned NumEAInputs = 0; // # of synthesized 'execute always' inputs.
923 for (unsigned ChildNo = 0, InstOpNo = NumResults;
924 InstOpNo != II.OperandList.size(); ++InstOpNo) {
925 std::vector<std::string> Ops;
926
927 // If this is a normal operand or a predicate operand without
928 // 'execute always', emit it.
929 Record *OperandNode = II.OperandList[InstOpNo].Rec;
930 if ((!OperandNode->isSubClassOf("PredicateOperand") &&
931 !OperandNode->isSubClassOf("OptionalDefOperand")) ||
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000932 CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
Evan Chengdb1f2462007-09-17 22:26:41 +0000933 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 InFlagDecled, ResNodeDecled);
935 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
936 ++ChildNo;
937 } else {
938 // Otherwise, this is a predicate or optional def operand, emit the
939 // 'default ops' operands.
940 const DAGDefaultOperand &DefaultOp =
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000941 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
Evan Chengdb1f2462007-09-17 22:26:41 +0000943 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000944 InFlagDecled, ResNodeDecled);
945 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
946 NumEAInputs += Ops.size();
947 }
948 }
949 }
950
Dan Gohmanf14b4472008-01-31 00:25:39 +0000951 // Generate MemOperandSDNodes nodes for each memory accesses covered by this
952 // pattern.
953 if (isRoot) {
954 std::vector<std::string>::const_iterator mi, mie;
955 for (mi = LSI.begin(), mie = LSI.end(); mi != mie; ++mi) {
956 emitCode("SDOperand LSI_" + *mi + " = "
957 "CurDAG->getMemOperand(cast<LSBaseSDNode>(" +
958 *mi + ")->getMemOperand());");
959 AllOps.push_back("LSI_" + *mi);
960 }
961 }
962
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000963 // Emit all the chain and CopyToReg stuff.
964 bool ChainEmitted = NodeHasChain;
965 if (NodeHasChain)
966 emitCode("AddToISelQueue(" + ChainName + ");");
967 if (NodeHasInFlag || HasImpInputs)
968 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
969 InFlagDecled, ResNodeDecled, true);
970 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
971 if (!InFlagDecled) {
972 emitCode("SDOperand InFlag(0, 0);");
973 InFlagDecled = true;
974 }
975 if (NodeHasOptInFlag) {
976 emitCode("if (HasInFlag) {");
977 emitCode(" InFlag = N.getOperand(N.getNumOperands()-1);");
978 emitCode(" AddToISelQueue(InFlag);");
979 emitCode("}");
980 }
981 }
982
983 unsigned ResNo = TmpNo++;
984 if (!isRoot || InputHasChain || NodeHasChain || NodeHasOutFlag ||
Evan Chengdec1dd12007-09-07 23:59:02 +0000985 NodeHasOptInFlag || HasImpResults) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000986 std::string Code;
987 std::string Code2;
988 std::string NodeName;
989 if (!isRoot) {
990 NodeName = "Tmp" + utostr(ResNo);
Dan Gohman875770e2007-07-24 22:58:00 +0000991 Code2 = "SDOperand " + NodeName + "(";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 } else {
993 NodeName = "ResNode";
994 if (!ResNodeDecled) {
995 Code2 = "SDNode *" + NodeName + " = ";
996 ResNodeDecled = true;
997 } else
998 Code2 = NodeName + " = ";
999 }
1000
Evan Cheng775baac2007-09-12 23:30:14 +00001001 Code += "CurDAG->getTargetNode(Opc" + utostr(OpcNo);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 unsigned OpsNo = OpcNo;
1003 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1004
1005 // Output order: results, chain, flags
1006 // Result types.
1007 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1008 Code += ", VT" + utostr(VTNo);
1009 emitVT(getEnumName(N->getTypeNum(0)));
1010 }
Evan Chengdec1dd12007-09-07 23:59:02 +00001011 // Add types for implicit results in physical registers, scheduler will
1012 // care of adding copyfromreg nodes.
Evan Cheng775baac2007-09-12 23:30:14 +00001013 for (unsigned i = 0; i < NumDstRegs; i++) {
1014 Record *RR = DstRegs[i];
1015 if (RR->isSubClassOf("Register")) {
1016 MVT::ValueType RVT = getRegisterValueType(RR, CGT);
1017 Code += ", " + getEnumName(RVT);
Evan Chengdec1dd12007-09-07 23:59:02 +00001018 }
1019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 if (NodeHasChain)
1021 Code += ", MVT::Other";
1022 if (NodeHasOutFlag)
1023 Code += ", MVT::Flag";
1024
1025 // Figure out how many fixed inputs the node has. This is important to
1026 // know which inputs are the variable ones if present.
1027 unsigned NumInputs = AllOps.size();
1028 NumInputs += NodeHasChain;
1029
1030 // Inputs.
1031 if (HasVarOps) {
1032 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1033 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1034 AllOps.clear();
1035 }
1036
1037 if (HasVarOps) {
1038 // Figure out whether any operands at the end of the op list are not
1039 // part of the variable section.
1040 std::string EndAdjust;
1041 if (NodeHasInFlag || HasImpInputs)
1042 EndAdjust = "-1"; // Always has one flag.
1043 else if (NodeHasOptInFlag)
1044 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1045
1046 emitCode("for (unsigned i = " + utostr(NumInputs - NumEAInputs) +
1047 ", e = N.getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1048
1049 emitCode(" AddToISelQueue(N.getOperand(i));");
1050 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N.getOperand(i));");
1051 emitCode("}");
1052 }
1053
1054 if (NodeHasChain) {
1055 if (HasVarOps)
1056 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1057 else
1058 AllOps.push_back(ChainName);
1059 }
1060
1061 if (HasVarOps) {
1062 if (NodeHasInFlag || HasImpInputs)
1063 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1064 else if (NodeHasOptInFlag) {
1065 emitCode("if (HasInFlag)");
1066 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1067 }
1068 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1069 ".size()";
1070 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
Evan Cheng775baac2007-09-12 23:30:14 +00001071 AllOps.push_back("InFlag");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001072
1073 unsigned NumOps = AllOps.size();
1074 if (NumOps) {
1075 if (!NodeHasOptInFlag && NumOps < 4) {
1076 for (unsigned i = 0; i != NumOps; ++i)
1077 Code += ", " + AllOps[i];
1078 } else {
1079 std::string OpsCode = "SDOperand Ops" + utostr(OpsNo) + "[] = { ";
1080 for (unsigned i = 0; i != NumOps; ++i) {
1081 OpsCode += AllOps[i];
1082 if (i != NumOps-1)
1083 OpsCode += ", ";
1084 }
1085 emitCode(OpsCode + " };");
1086 Code += ", Ops" + utostr(OpsNo) + ", ";
1087 if (NodeHasOptInFlag) {
1088 Code += "HasInFlag ? ";
1089 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1090 } else
1091 Code += utostr(NumOps);
1092 }
1093 }
1094
1095 if (!isRoot)
1096 Code += "), 0";
1097 emitCode(Code2 + Code + ");");
1098
1099 if (NodeHasChain)
1100 // Remember which op produces the chain.
1101 if (!isRoot)
1102 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng775baac2007-09-12 23:30:14 +00001103 ".Val, " + utostr(NumResults+NumDstRegs) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001104 else
1105 emitCode(ChainName + " = SDOperand(" + NodeName +
Evan Cheng775baac2007-09-12 23:30:14 +00001106 ", " + utostr(NumResults+NumDstRegs) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001107
1108 if (!isRoot) {
1109 NodeOps.push_back("Tmp" + utostr(ResNo));
1110 return NodeOps;
1111 }
1112
1113 bool NeedReplace = false;
1114 if (NodeHasOutFlag) {
1115 if (!InFlagDecled) {
Dan Gohman875770e2007-07-24 22:58:00 +00001116 emitCode("SDOperand InFlag(ResNode, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001117 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001118 InFlagDecled = true;
1119 } else
1120 emitCode("InFlag = SDOperand(ResNode, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001121 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001122 }
1123
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124 if (FoldedChains.size() > 0) {
1125 std::string Code;
1126 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++)
1127 emitCode("ReplaceUses(SDOperand(" +
1128 FoldedChains[j].first + ".Val, " +
1129 utostr(FoldedChains[j].second) + "), SDOperand(ResNode, " +
Evan Cheng775baac2007-09-12 23:30:14 +00001130 utostr(NumResults+NumDstRegs) + "));");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 NeedReplace = true;
1132 }
1133
1134 if (NodeHasOutFlag) {
1135 emitCode("ReplaceUses(SDOperand(N.Val, " +
Evan Chengdb1f2462007-09-17 22:26:41 +00001136 utostr(NumPatResults + (unsigned)InputHasChain)
1137 +"), InFlag);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 NeedReplace = true;
1139 }
1140
Evan Chengdb1f2462007-09-17 22:26:41 +00001141 if (NeedReplace && InputHasChain)
1142 emitCode("ReplaceUses(SDOperand(N.Val, " +
1143 utostr(NumPatResults) + "), SDOperand(" + ChainName
1144 + ".Val, " + ChainName + ".ResNo" + "));");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001145
1146 // User does not expect the instruction would produce a chain!
1147 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1148 ;
1149 } else if (InputHasChain && !NodeHasChain) {
1150 // One of the inner node produces a chain.
1151 if (NodeHasOutFlag)
Evan Cheng775baac2007-09-12 23:30:14 +00001152 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults+1) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001153 "), SDOperand(ResNode, N.ResNo-1));");
Evan Cheng775baac2007-09-12 23:30:14 +00001154 emitCode("ReplaceUses(SDOperand(N.Val, " + utostr(NumPatResults) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001155 "), " + ChainName + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001156 }
1157
Evan Chengdb1f2462007-09-17 22:26:41 +00001158 emitCode("return ResNode;");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001159 } else {
1160 std::string Code = "return CurDAG->SelectNodeTo(N.Val, Opc" +
1161 utostr(OpcNo);
1162 if (N->getTypeNum(0) != MVT::isVoid)
1163 Code += ", VT" + utostr(VTNo);
1164 if (NodeHasOutFlag)
1165 Code += ", MVT::Flag";
1166
1167 if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1168 AllOps.push_back("InFlag");
1169
1170 unsigned NumOps = AllOps.size();
1171 if (NumOps) {
1172 if (!NodeHasOptInFlag && NumOps < 4) {
1173 for (unsigned i = 0; i != NumOps; ++i)
1174 Code += ", " + AllOps[i];
1175 } else {
1176 std::string OpsCode = "SDOperand Ops" + utostr(OpcNo) + "[] = { ";
1177 for (unsigned i = 0; i != NumOps; ++i) {
1178 OpsCode += AllOps[i];
1179 if (i != NumOps-1)
1180 OpsCode += ", ";
1181 }
1182 emitCode(OpsCode + " };");
1183 Code += ", Ops" + utostr(OpcNo) + ", ";
1184 Code += utostr(NumOps);
1185 }
1186 }
1187 emitCode(Code + ");");
1188 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1189 if (N->getTypeNum(0) != MVT::isVoid)
1190 emitVT(getEnumName(N->getTypeNum(0)));
1191 }
1192
1193 return NodeOps;
1194 } else if (Op->isSubClassOf("SDNodeXForm")) {
1195 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1196 // PatLeaf node - the operand may or may not be a leaf node. But it should
1197 // behave like one.
1198 std::vector<std::string> Ops =
Evan Chengdb1f2462007-09-17 22:26:41 +00001199 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200 ResNodeDecled, true);
1201 unsigned ResNo = TmpNo++;
1202 emitCode("SDOperand Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1203 + "(" + Ops.back() + ".Val);");
1204 NodeOps.push_back("Tmp" + utostr(ResNo));
1205 if (isRoot)
1206 emitCode("return Tmp" + utostr(ResNo) + ".Val;");
1207 return NodeOps;
1208 } else {
1209 N->dump();
1210 cerr << "\n";
1211 throw std::string("Unknown node in result pattern!");
1212 }
1213 }
1214
1215 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
1216 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
1217 /// 'Pat' may be missing types. If we find an unresolved type to add a check
1218 /// for, this returns true otherwise false if Pat has all types.
1219 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
1220 const std::string &Prefix, bool isRoot = false) {
1221 // Did we find one?
1222 if (Pat->getExtTypes() != Other->getExtTypes()) {
1223 // Move a type over from 'other' to 'pat'.
1224 Pat->setTypes(Other->getExtTypes());
1225 // The top level node type is checked outside of the select function.
1226 if (!isRoot)
1227 emitCheck(Prefix + ".Val->getValueType(0) == " +
1228 getName(Pat->getTypeNum(0)));
1229 return true;
1230 }
1231
1232 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001233 (unsigned) NodeHasProperty(Pat, SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001234 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
1235 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
1236 Prefix + utostr(OpNo)))
1237 return true;
1238 return false;
1239 }
1240
1241private:
1242 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
1243 /// being built.
1244 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
1245 bool &ChainEmitted, bool &InFlagDecled,
1246 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001247 const CodeGenTarget &T = CGP.getTargetInfo();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001248 unsigned OpNo =
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001249 (unsigned) NodeHasProperty(N, SDNPHasChain, CGP);
1250 bool HasInFlag = NodeHasProperty(N, SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
1252 TreePatternNode *Child = N->getChild(i);
1253 if (!Child->isLeaf()) {
1254 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
1255 InFlagDecled, ResNodeDecled);
1256 } else {
1257 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
1258 if (!Child->getName().empty()) {
1259 std::string Name = RootName + utostr(OpNo);
1260 if (Duplicates.find(Name) != Duplicates.end())
1261 // A duplicate! Do not emit a copy for this node.
1262 continue;
1263 }
1264
1265 Record *RR = DI->getDef();
1266 if (RR->isSubClassOf("Register")) {
1267 MVT::ValueType RVT = getRegisterValueType(RR, T);
1268 if (RVT == MVT::Flag) {
1269 if (!InFlagDecled) {
1270 emitCode("SDOperand InFlag = " + RootName + utostr(OpNo) + ";");
1271 InFlagDecled = true;
1272 } else
1273 emitCode("InFlag = " + RootName + utostr(OpNo) + ";");
1274 emitCode("AddToISelQueue(InFlag);");
1275 } else {
1276 if (!ChainEmitted) {
1277 emitCode("SDOperand Chain = CurDAG->getEntryNode();");
1278 ChainName = "Chain";
1279 ChainEmitted = true;
1280 }
1281 emitCode("AddToISelQueue(" + RootName + utostr(OpNo) + ");");
1282 if (!InFlagDecled) {
1283 emitCode("SDOperand InFlag(0, 0);");
1284 InFlagDecled = true;
1285 }
1286 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
1287 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001288 ", " + getQualifiedName(RR) +
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001289 ", " + RootName + utostr(OpNo) + ", InFlag).Val;");
1290 ResNodeDecled = true;
1291 emitCode(ChainName + " = SDOperand(ResNode, 0);");
1292 emitCode("InFlag = SDOperand(ResNode, 1);");
1293 }
1294 }
1295 }
1296 }
1297 }
1298
1299 if (HasInFlag) {
1300 if (!InFlagDecled) {
1301 emitCode("SDOperand InFlag = " + RootName +
1302 ".getOperand(" + utostr(OpNo) + ");");
1303 InFlagDecled = true;
1304 } else
1305 emitCode("InFlag = " + RootName +
1306 ".getOperand(" + utostr(OpNo) + ");");
1307 emitCode("AddToISelQueue(InFlag);");
1308 }
1309 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001310};
1311
1312/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1313/// stream to match the pattern, and generate the code for the match if it
1314/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001315void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001316 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1317 std::set<std::string> &GeneratedDecl,
1318 std::vector<std::string> &TargetOpcodes,
1319 std::vector<std::string> &TargetVTs) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001320 PatternCodeEmitter Emitter(CGP, Pattern.getPredicates(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1322 GeneratedCode, GeneratedDecl,
1323 TargetOpcodes, TargetVTs);
1324
1325 // Emit the matcher, capturing named arguments in VariableMap.
1326 bool FoundChain = false;
1327 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1328
1329 // TP - Get *SOME* tree pattern, we don't care which.
Chris Lattner14948ea2008-01-05 22:58:54 +00001330 TreePattern &TP = *CGP.pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331
1332 // At this point, we know that we structurally match the pattern, but the
1333 // types of the nodes may not match. Figure out the fewest number of type
1334 // comparisons we need to emit. For example, if there is only one integer
1335 // type supported by a target, there should be no type comparisons at all for
1336 // integer patterns!
1337 //
1338 // To figure out the fewest number of type checks needed, clone the pattern,
1339 // remove the types, then perform type inference on the pattern as a whole.
1340 // If there are unresolved types, emit an explicit check for those types,
1341 // apply the type to the tree, then rerun type inference. Iterate until all
1342 // types are resolved.
1343 //
1344 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
1345 RemoveAllTypes(Pat);
1346
1347 do {
1348 // Resolve/propagate as many types as possible.
1349 try {
1350 bool MadeChange = true;
1351 while (MadeChange)
1352 MadeChange = Pat->ApplyTypeConstraints(TP,
1353 true/*Ignore reg constraints*/);
1354 } catch (...) {
1355 assert(0 && "Error: could not find consistent types for something we"
1356 " already decided was ok!");
1357 abort();
1358 }
1359
1360 // Insert a check for an unresolved type and add it to the tree. If we find
1361 // an unresolved type to add a check for, this returns true and we iterate,
1362 // otherwise we are done.
1363 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1364
Evan Cheng775baac2007-09-12 23:30:14 +00001365 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001366 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367 delete Pat;
1368}
1369
1370/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1371/// a line causes any of them to be empty, remove them and return true when
1372/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001373static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001374 std::vector<std::pair<unsigned, std::string> > > >
1375 &Patterns) {
1376 bool ErasedPatterns = false;
1377 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1378 Patterns[i].second.pop_back();
1379 if (Patterns[i].second.empty()) {
1380 Patterns.erase(Patterns.begin()+i);
1381 --i; --e;
1382 ErasedPatterns = true;
1383 }
1384 }
1385 return ErasedPatterns;
1386}
1387
1388/// EmitPatterns - Emit code for at least one pattern, but try to group common
1389/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001390void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001391 std::vector<std::pair<unsigned, std::string> > > >
1392 &Patterns, unsigned Indent,
1393 std::ostream &OS) {
1394 typedef std::pair<unsigned, std::string> CodeLine;
1395 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001396 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397
1398 if (Patterns.empty()) return;
1399
1400 // Figure out how many patterns share the next code line. Explicitly copy
1401 // FirstCodeLine so that we don't invalidate a reference when changing
1402 // Patterns.
1403 const CodeLine FirstCodeLine = Patterns.back().second.back();
1404 unsigned LastMatch = Patterns.size()-1;
1405 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1406 --LastMatch;
1407
1408 // If not all patterns share this line, split the list into two pieces. The
1409 // first chunk will use this line, the second chunk won't.
1410 if (LastMatch != 0) {
1411 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1412 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1413
1414 // FIXME: Emit braces?
1415 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001416 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001417 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1418 Pattern.getSrcPattern()->print(OS);
1419 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1420 Pattern.getDstPattern()->print(OS);
1421 OS << "\n";
1422 unsigned AddedComplexity = Pattern.getAddedComplexity();
1423 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001424 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001426 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001428 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 }
1430 if (FirstCodeLine.first != 1) {
1431 OS << std::string(Indent, ' ') << "{\n";
1432 Indent += 2;
1433 }
1434 EmitPatterns(Shared, Indent, OS);
1435 if (FirstCodeLine.first != 1) {
1436 Indent -= 2;
1437 OS << std::string(Indent, ' ') << "}\n";
1438 }
1439
1440 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001441 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001442 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1443 Pattern.getSrcPattern()->print(OS);
1444 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1445 Pattern.getDstPattern()->print(OS);
1446 OS << "\n";
1447 unsigned AddedComplexity = Pattern.getAddedComplexity();
1448 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001449 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001451 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001452 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001453 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001454 }
1455 EmitPatterns(Other, Indent, OS);
1456 return;
1457 }
1458
1459 // Remove this code from all of the patterns that share it.
1460 bool ErasedPatterns = EraseCodeLine(Patterns);
1461
1462 bool isPredicate = FirstCodeLine.first == 1;
1463
1464 // Otherwise, every pattern in the list has this line. Emit it.
1465 if (!isPredicate) {
1466 // Normal code.
1467 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1468 } else {
1469 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1470
1471 // If the next code line is another predicate, and if all of the pattern
1472 // in this group share the same next line, emit it inline now. Do this
1473 // until we run out of common predicates.
1474 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
1475 // Check that all of fhe patterns in Patterns end with the same predicate.
1476 bool AllEndWithSamePredicate = true;
1477 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1478 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1479 AllEndWithSamePredicate = false;
1480 break;
1481 }
1482 // If all of the predicates aren't the same, we can't share them.
1483 if (!AllEndWithSamePredicate) break;
1484
1485 // Otherwise we can. Emit it shared now.
1486 OS << " &&\n" << std::string(Indent+4, ' ')
1487 << Patterns.back().second.back().second;
1488 ErasedPatterns = EraseCodeLine(Patterns);
1489 }
1490
1491 OS << ") {\n";
1492 Indent += 2;
1493 }
1494
1495 EmitPatterns(Patterns, Indent, OS);
1496
1497 if (isPredicate)
1498 OS << std::string(Indent-2, ' ') << "}\n";
1499}
1500
Chris Lattnerae506702008-01-06 01:10:31 +00001501static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001502 return CGP.getSDNodeInfo(Op).getEnumName();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001503}
1504
1505static std::string getLegalCName(std::string OpName) {
1506 std::string::size_type pos = OpName.find("::");
1507 if (pos != std::string::npos)
1508 OpName.replace(pos, 2, "_");
1509 return OpName;
1510}
1511
1512void DAGISelEmitter::EmitInstructionSelector(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001513 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001514
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 // Get the namespace to insert instructions into. Make sure not to pick up
1516 // "TargetInstrInfo" by accidentally getting the namespace off the PHI
1517 // instruction or something.
1518 std::string InstNS;
1519 for (CodeGenTarget::inst_iterator i = Target.inst_begin(),
1520 e = Target.inst_end(); i != e; ++i) {
1521 InstNS = i->second.Namespace;
1522 if (InstNS != "TargetInstrInfo")
1523 break;
1524 }
1525
1526 if (!InstNS.empty()) InstNS += "::";
1527
1528 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001529 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 // All unique target node emission functions.
1531 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerae506702008-01-06 01:10:31 +00001532 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001533 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001534 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001535
1536 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 if (!Node->isLeaf()) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001538 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001539 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 } else {
1541 const ComplexPattern *CP;
1542 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001543 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001544 push_back(&Pattern);
Chris Lattner14948ea2008-01-05 22:58:54 +00001545 } else if ((CP = NodeGetComplexPattern(Node, CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001546 std::vector<Record*> OpNodes = CP->getRootNodes();
1547 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001548 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1549 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001550 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001551 }
1552 } else {
1553 cerr << "Unrecognized opcode '";
1554 Node->dump();
1555 cerr << "' on tree pattern '";
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001556 cerr << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001557 exit(1);
1558 }
1559 }
1560 }
1561
1562 // For each opcode, there might be multiple select functions, one per
1563 // ValueType of the node (or its first operand if it doesn't produce a
1564 // non-chain result.
1565 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1566
1567 // Emit one Select_* method for each top-level opcode. We do this instead of
1568 // emitting one giant switch statement to support compilers where this will
1569 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001570 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001571 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1572 PBOI != E; ++PBOI) {
1573 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001574 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1576
1577 // We want to emit all of the matching code now. However, we want to emit
1578 // the matches in order of minimal cost. Sort the patterns so the least
1579 // cost one is at the start.
1580 std::stable_sort(PatternsOfOp.begin(), PatternsOfOp.end(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001581 PatternSortingPredicate(CGP));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001582
1583 // Split them into groups by type.
Chris Lattner81915752008-01-05 22:30:17 +00001584 std::map<MVT::ValueType, std::vector<const PatternToMatch*> >PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001585 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001586 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001587 TreePatternNode *SrcPat = Pat->getSrcPattern();
1588 MVT::ValueType VT = SrcPat->getTypeNum(0);
Chris Lattner81915752008-01-05 22:30:17 +00001589 std::map<MVT::ValueType,
1590 std::vector<const PatternToMatch*> >::iterator TI =
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001591 PatternsByType.find(VT);
1592 if (TI != PatternsByType.end())
1593 TI->second.push_back(Pat);
1594 else {
Chris Lattner81915752008-01-05 22:30:17 +00001595 std::vector<const PatternToMatch*> PVec;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001596 PVec.push_back(Pat);
1597 PatternsByType.insert(std::make_pair(VT, PVec));
1598 }
1599 }
1600
Chris Lattner81915752008-01-05 22:30:17 +00001601 for (std::map<MVT::ValueType, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001602 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1603 ++II) {
1604 MVT::ValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001605 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 typedef std::vector<std::pair<unsigned,std::string> > CodeList;
1607 typedef std::vector<std::pair<unsigned,std::string> >::iterator CodeListI;
1608
Chris Lattner81915752008-01-05 22:30:17 +00001609 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001610 std::vector<std::vector<std::string> > PatternOpcodes;
1611 std::vector<std::vector<std::string> > PatternVTs;
1612 std::vector<std::set<std::string> > PatternDecls;
1613 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1614 CodeList GeneratedCode;
1615 std::set<std::string> GeneratedDecl;
1616 std::vector<std::string> TargetOpcodes;
1617 std::vector<std::string> TargetVTs;
1618 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
1619 TargetOpcodes, TargetVTs);
1620 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1621 PatternDecls.push_back(GeneratedDecl);
1622 PatternOpcodes.push_back(TargetOpcodes);
1623 PatternVTs.push_back(TargetVTs);
1624 }
1625
1626 // Scan the code to see if all of the patterns are reachable and if it is
1627 // possible that the last one might not match.
1628 bool mightNotMatch = true;
1629 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1630 CodeList &GeneratedCode = CodeForPatterns[i].second;
1631 mightNotMatch = false;
1632
1633 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1634 if (GeneratedCode[j].first == 1) { // predicate.
1635 mightNotMatch = true;
1636 break;
1637 }
1638 }
1639
1640 // If this pattern definitely matches, and if it isn't the last one, the
1641 // patterns after it CANNOT ever match. Error out.
1642 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
1643 cerr << "Pattern '";
1644 CodeForPatterns[i].first->getSrcPattern()->print(*cerr.stream());
1645 cerr << "' is impossible to select!\n";
1646 exit(1);
1647 }
1648 }
1649
1650 // Factor target node emission code (emitted by EmitResultCode) into
1651 // separate functions. Uniquing and share them among all instruction
1652 // selection routines.
1653 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1654 CodeList &GeneratedCode = CodeForPatterns[i].second;
1655 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1656 std::vector<std::string> &TargetVTs = PatternVTs[i];
1657 std::set<std::string> Decls = PatternDecls[i];
1658 std::vector<std::string> AddedInits;
1659 int CodeSize = (int)GeneratedCode.size();
1660 int LastPred = -1;
1661 for (int j = CodeSize-1; j >= 0; --j) {
1662 if (LastPred == -1 && GeneratedCode[j].first == 1)
1663 LastPred = j;
1664 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1665 AddedInits.push_back(GeneratedCode[j].second);
1666 }
1667
1668 std::string CalleeCode = "(const SDOperand &N";
1669 std::string CallerCode = "(N";
1670 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1671 CalleeCode += ", unsigned Opc" + utostr(j);
1672 CallerCode += ", " + TargetOpcodes[j];
1673 }
1674 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
1675 CalleeCode += ", MVT::ValueType VT" + utostr(j);
1676 CallerCode += ", " + TargetVTs[j];
1677 }
1678 for (std::set<std::string>::iterator
1679 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1680 std::string Name = *I;
1681 CalleeCode += ", SDOperand &" + Name;
1682 CallerCode += ", " + Name;
1683 }
1684 CallerCode += ");";
1685 CalleeCode += ") ";
1686 // Prevent emission routines from being inlined to reduce selection
1687 // routines stack frame sizes.
1688 CalleeCode += "DISABLE_INLINE ";
1689 CalleeCode += "{\n";
1690
1691 for (std::vector<std::string>::const_reverse_iterator
1692 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1693 CalleeCode += " " + *I + "\n";
1694
1695 for (int j = LastPred+1; j < CodeSize; ++j)
1696 CalleeCode += " " + GeneratedCode[j].second + "\n";
1697 for (int j = LastPred+1; j < CodeSize; ++j)
1698 GeneratedCode.pop_back();
1699 CalleeCode += "}\n";
1700
1701 // Uniquing the emission routines.
1702 unsigned EmitFuncNum;
1703 std::map<std::string, unsigned>::iterator EFI =
1704 EmitFunctions.find(CalleeCode);
1705 if (EFI != EmitFunctions.end()) {
1706 EmitFuncNum = EFI->second;
1707 } else {
1708 EmitFuncNum = EmitFunctions.size();
1709 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
1710 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1711 }
1712
1713 // Replace the emission code within selection routines with calls to the
1714 // emission functions.
1715 CallerCode = "return Emit_" + utostr(EmitFuncNum) + CallerCode;
1716 GeneratedCode.push_back(std::make_pair(false, CallerCode));
1717 }
1718
1719 // Print function.
1720 std::string OpVTStr;
1721 if (OpVT == MVT::iPTR) {
1722 OpVTStr = "_iPTR";
1723 } else if (OpVT == MVT::isVoid) {
1724 // Nodes with a void result actually have a first result type of either
1725 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1726 // void to this case, we handle it specially here.
1727 } else {
1728 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
1729 }
1730 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1731 OpcodeVTMap.find(OpName);
1732 if (OpVTI == OpcodeVTMap.end()) {
1733 std::vector<std::string> VTSet;
1734 VTSet.push_back(OpVTStr);
1735 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1736 } else
1737 OpVTI->second.push_back(OpVTStr);
1738
1739 OS << "SDNode *Select_" << getLegalCName(OpName)
1740 << OpVTStr << "(const SDOperand &N) {\n";
1741
1742 // Loop through and reverse all of the CodeList vectors, as we will be
1743 // accessing them from their logical front, but accessing the end of a
1744 // vector is more efficient.
1745 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1746 CodeList &GeneratedCode = CodeForPatterns[i].second;
1747 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1748 }
1749
1750 // Next, reverse the list of patterns itself for the same reason.
1751 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1752
1753 // Emit all of the patterns now, grouped together to share code.
1754 EmitPatterns(CodeForPatterns, 2, OS);
1755
1756 // If the last pattern has predicates (which could fail) emit code to
1757 // catch the case where nothing handles a pattern.
1758 if (mightNotMatch) {
1759 OS << " cerr << \"Cannot yet select: \";\n";
1760 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1761 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
1762 OpName != "ISD::INTRINSIC_VOID") {
1763 OS << " N.Val->dump(CurDAG);\n";
1764 } else {
1765 OS << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1766 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1767 << " cerr << \"intrinsic %\"<< "
1768 "Intrinsic::getName((Intrinsic::ID)iid);\n";
1769 }
1770 OS << " cerr << '\\n';\n"
1771 << " abort();\n"
1772 << " return NULL;\n";
1773 }
1774 OS << "}\n\n";
1775 }
1776 }
1777
1778 // Emit boilerplate.
1779 OS << "SDNode *Select_INLINEASM(SDOperand N) {\n"
1780 << " std::vector<SDOperand> Ops(N.Val->op_begin(), N.Val->op_end());\n"
1781 << " SelectInlineAsmMemoryOperands(Ops, *CurDAG);\n\n"
1782
1783 << " // Ensure that the asm operands are themselves selected.\n"
1784 << " for (unsigned j = 0, e = Ops.size(); j != e; ++j)\n"
1785 << " AddToISelQueue(Ops[j]);\n\n"
1786
1787 << " std::vector<MVT::ValueType> VTs;\n"
1788 << " VTs.push_back(MVT::Other);\n"
1789 << " VTs.push_back(MVT::Flag);\n"
1790 << " SDOperand New = CurDAG->getNode(ISD::INLINEASM, VTs, &Ops[0], "
1791 "Ops.size());\n"
1792 << " return New.Val;\n"
1793 << "}\n\n";
1794
1795 OS << "SDNode *Select_LABEL(const SDOperand &N) {\n"
1796 << " SDOperand Chain = N.getOperand(0);\n"
1797 << " SDOperand N1 = N.getOperand(1);\n"
1798 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1799 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1800 << " AddToISelQueue(Chain);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001801 << " SDOperand Ops[] = { Tmp, Chain };\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001802 << " return CurDAG->getTargetNode(TargetInstrInfo::LABEL,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001803 << " MVT::Other, Ops, 2);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001804 << "}\n\n";
1805
Christopher Lamb071a2a72007-07-26 07:48:21 +00001806 OS << "SDNode *Select_EXTRACT_SUBREG(const SDOperand &N) {\n"
1807 << " SDOperand N0 = N.getOperand(0);\n"
1808 << " SDOperand N1 = N.getOperand(1);\n"
1809 << " unsigned C = cast<ConstantSDNode>(N1)->getValue();\n"
1810 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1811 << " AddToISelQueue(N0);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001812 << " SDOperand Ops[] = { N0, Tmp };\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001813 << " return CurDAG->getTargetNode(TargetInstrInfo::EXTRACT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001814 << " N.getValueType(), Ops, 2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001815 << "}\n\n";
1816
1817 OS << "SDNode *Select_INSERT_SUBREG(const SDOperand &N) {\n"
1818 << " SDOperand N0 = N.getOperand(0);\n"
1819 << " SDOperand N1 = N.getOperand(1);\n"
1820 << " SDOperand N2 = N.getOperand(2);\n"
1821 << " unsigned C = cast<ConstantSDNode>(N2)->getValue();\n"
1822 << " SDOperand Tmp = CurDAG->getTargetConstant(C, MVT::i32);\n"
1823 << " AddToISelQueue(N1);\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001824 << " SDOperand Ops[] = { N0, N1, Tmp };\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001825 << " if (N0.getOpcode() == ISD::UNDEF) {\n"
Evan Cheng2929a8e2007-10-12 08:39:02 +00001826 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001827 << " N.getValueType(), Ops+1, 2);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001828 << " } else {\n"
1829 << " AddToISelQueue(N0);\n"
Evan Cheng2929a8e2007-10-12 08:39:02 +00001830 << " return CurDAG->getTargetNode(TargetInstrInfo::INSERT_SUBREG,\n"
Chris Lattner56af5402007-10-24 06:25:09 +00001831 << " N.getValueType(), Ops, 3);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001832 << " }\n"
1833 << "}\n\n";
1834
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001835 OS << "// The main instruction selector code.\n"
1836 << "SDNode *SelectCode(SDOperand N) {\n"
1837 << " if (N.getOpcode() >= ISD::BUILTIN_OP_END &&\n"
1838 << " N.getOpcode() < (ISD::BUILTIN_OP_END+" << InstNS
1839 << "INSTRUCTION_LIST_END)) {\n"
1840 << " return NULL; // Already selected.\n"
1841 << " }\n\n"
1842 << " MVT::ValueType NVT = N.Val->getValueType(0);\n"
1843 << " switch (N.getOpcode()) {\n"
1844 << " default: break;\n"
1845 << " case ISD::EntryToken: // These leaves remain the same.\n"
1846 << " case ISD::BasicBlock:\n"
1847 << " case ISD::Register:\n"
1848 << " case ISD::HANDLENODE:\n"
1849 << " case ISD::TargetConstant:\n"
1850 << " case ISD::TargetConstantPool:\n"
1851 << " case ISD::TargetFrameIndex:\n"
1852 << " case ISD::TargetExternalSymbol:\n"
1853 << " case ISD::TargetJumpTable:\n"
1854 << " case ISD::TargetGlobalTLSAddress:\n"
1855 << " case ISD::TargetGlobalAddress: {\n"
1856 << " return NULL;\n"
1857 << " }\n"
1858 << " case ISD::AssertSext:\n"
1859 << " case ISD::AssertZext: {\n"
1860 << " AddToISelQueue(N.getOperand(0));\n"
1861 << " ReplaceUses(N, N.getOperand(0));\n"
1862 << " return NULL;\n"
1863 << " }\n"
1864 << " case ISD::TokenFactor:\n"
1865 << " case ISD::CopyFromReg:\n"
1866 << " case ISD::CopyToReg: {\n"
1867 << " for (unsigned i = 0, e = N.getNumOperands(); i != e; ++i)\n"
1868 << " AddToISelQueue(N.getOperand(i));\n"
1869 << " return NULL;\n"
1870 << " }\n"
1871 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Christopher Lamb071a2a72007-07-26 07:48:21 +00001872 << " case ISD::LABEL: return Select_LABEL(N);\n"
1873 << " case ISD::EXTRACT_SUBREG: return Select_EXTRACT_SUBREG(N);\n"
1874 << " case ISD::INSERT_SUBREG: return Select_INSERT_SUBREG(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001875
1876
1877 // Loop over all of the case statements, emiting a call to each method we
1878 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00001879 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001880 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1881 PBOI != E; ++PBOI) {
1882 const std::string &OpName = PBOI->first;
1883 // Potentially multiple versions of select for this opcode. One for each
1884 // ValueType of the node (or its first true operand if it doesn't produce a
1885 // result.
1886 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1887 OpcodeVTMap.find(OpName);
1888 std::vector<std::string> &OpVTs = OpVTI->second;
1889 OS << " case " << OpName << ": {\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00001890 // Keep track of whether we see a pattern that has an iPtr result.
1891 bool HasPtrPattern = false;
1892 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893
Evan Chengb8b6b182007-09-04 20:18:28 +00001894 OS << " switch (NVT) {\n";
1895 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1896 std::string &VTStr = OpVTs[i];
1897 if (VTStr.empty()) {
1898 HasDefaultPattern = true;
1899 continue;
1900 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001901
Evan Chengb8b6b182007-09-04 20:18:28 +00001902 // If this is a match on iPTR: don't emit it directly, we need special
1903 // code.
1904 if (VTStr == "_iPTR") {
1905 HasPtrPattern = true;
1906 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001908 OS << " case MVT::" << VTStr.substr(1) << ":\n"
1909 << " return Select_" << getLegalCName(OpName)
1910 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001911 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001912 OS << " default:\n";
1913
1914 // If there is an iPTR result version of this pattern, emit it here.
1915 if (HasPtrPattern) {
1916 OS << " if (NVT == TLI.getPointerTy())\n";
1917 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1918 }
1919 if (HasDefaultPattern) {
1920 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1921 }
1922 OS << " break;\n";
1923 OS << " }\n";
1924 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001925 OS << " }\n";
1926 }
1927
1928 OS << " } // end of big switch.\n\n"
1929 << " cerr << \"Cannot yet select: \";\n"
1930 << " if (N.getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1931 << " N.getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1932 << " N.getOpcode() != ISD::INTRINSIC_VOID) {\n"
1933 << " N.Val->dump(CurDAG);\n"
1934 << " } else {\n"
1935 << " unsigned iid = cast<ConstantSDNode>(N.getOperand("
1936 "N.getOperand(0).getValueType() == MVT::Other))->getValue();\n"
1937 << " cerr << \"intrinsic %\"<< "
1938 "Intrinsic::getName((Intrinsic::ID)iid);\n"
1939 << " }\n"
1940 << " cerr << '\\n';\n"
1941 << " abort();\n"
1942 << " return NULL;\n"
1943 << "}\n";
1944}
1945
1946void DAGISelEmitter::run(std::ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001947 EmitSourceFileHeader("DAG Instruction Selector for the " +
1948 CGP.getTargetInfo().getName() + " target", OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001949
1950 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1951 << "// *** instruction selector class. These functions are really "
1952 << "methods.\n\n";
1953
1954 OS << "#include \"llvm/Support/Compiler.h\"\n";
1955
1956 OS << "// Instruction selector priority queue:\n"
1957 << "std::vector<SDNode*> ISelQueue;\n";
1958 OS << "/// Keep track of nodes which have already been added to queue.\n"
1959 << "unsigned char *ISelQueued;\n";
1960 OS << "/// Keep track of nodes which have already been selected.\n"
1961 << "unsigned char *ISelSelected;\n";
1962 OS << "/// Dummy parameter to ReplaceAllUsesOfValueWith().\n"
1963 << "std::vector<SDNode*> ISelKilled;\n\n";
1964
1965 OS << "/// IsChainCompatible - Returns true if Chain is Op or Chain does\n";
1966 OS << "/// not reach Op.\n";
1967 OS << "static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {\n";
1968 OS << " if (Chain->getOpcode() == ISD::EntryToken)\n";
1969 OS << " return true;\n";
1970 OS << " else if (Chain->getOpcode() == ISD::TokenFactor)\n";
1971 OS << " return false;\n";
1972 OS << " else if (Chain->getNumOperands() > 0) {\n";
1973 OS << " SDOperand C0 = Chain->getOperand(0);\n";
1974 OS << " if (C0.getValueType() == MVT::Other)\n";
1975 OS << " return C0.Val != Op && IsChainCompatible(C0.Val, Op);\n";
1976 OS << " }\n";
1977 OS << " return true;\n";
1978 OS << "}\n";
1979
1980 OS << "/// Sorting functions for the selection queue.\n"
1981 << "struct isel_sort : public std::binary_function"
1982 << "<SDNode*, SDNode*, bool> {\n"
1983 << " bool operator()(const SDNode* left, const SDNode* right) "
1984 << "const {\n"
1985 << " return (left->getNodeId() > right->getNodeId());\n"
1986 << " }\n"
1987 << "};\n\n";
1988
1989 OS << "inline void setQueued(int Id) {\n";
1990 OS << " ISelQueued[Id / 8] |= 1 << (Id % 8);\n";
1991 OS << "}\n";
1992 OS << "inline bool isQueued(int Id) {\n";
1993 OS << " return ISelQueued[Id / 8] & (1 << (Id % 8));\n";
1994 OS << "}\n";
1995 OS << "inline void setSelected(int Id) {\n";
1996 OS << " ISelSelected[Id / 8] |= 1 << (Id % 8);\n";
1997 OS << "}\n";
1998 OS << "inline bool isSelected(int Id) {\n";
1999 OS << " return ISelSelected[Id / 8] & (1 << (Id % 8));\n";
2000 OS << "}\n\n";
2001
2002 OS << "void AddToISelQueue(SDOperand N) DISABLE_INLINE {\n";
2003 OS << " int Id = N.Val->getNodeId();\n";
2004 OS << " if (Id != -1 && !isQueued(Id)) {\n";
2005 OS << " ISelQueue.push_back(N.Val);\n";
2006 OS << " std::push_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2007 OS << " setQueued(Id);\n";
2008 OS << " }\n";
2009 OS << "}\n\n";
2010
2011 OS << "inline void RemoveKilled() {\n";
2012OS << " unsigned NumKilled = ISelKilled.size();\n";
2013 OS << " if (NumKilled) {\n";
2014 OS << " for (unsigned i = 0; i != NumKilled; ++i) {\n";
2015 OS << " SDNode *Temp = ISelKilled[i];\n";
2016 OS << " ISelQueue.erase(std::remove(ISelQueue.begin(), ISelQueue.end(), "
2017 << "Temp), ISelQueue.end());\n";
2018 OS << " };\n";
2019 OS << " std::make_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2020 OS << " ISelKilled.clear();\n";
2021 OS << " }\n";
2022 OS << "}\n\n";
2023
2024 OS << "void ReplaceUses(SDOperand F, SDOperand T) DISABLE_INLINE {\n";
Chris Lattner8a258202007-10-15 06:10:22 +00002025 OS << " CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISelKilled);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002026 OS << " setSelected(F.Val->getNodeId());\n";
2027 OS << " RemoveKilled();\n";
2028 OS << "}\n";
Evan Cheng775baac2007-09-12 23:30:14 +00002029 OS << "void ReplaceUses(SDNode *F, SDNode *T) DISABLE_INLINE {\n";
Evan Chengdb1f2462007-09-17 22:26:41 +00002030 OS << " unsigned FNumVals = F->getNumValues();\n";
2031 OS << " unsigned TNumVals = T->getNumValues();\n";
2032 OS << " if (FNumVals != TNumVals) {\n";
2033 OS << " for (unsigned i = 0, e = std::min(FNumVals, TNumVals); "
2034 << "i < e; ++i)\n";
Evan Cheng775baac2007-09-12 23:30:14 +00002035 OS << " CurDAG->ReplaceAllUsesOfValueWith(SDOperand(F, i), "
Chris Lattner8a258202007-10-15 06:10:22 +00002036 << "SDOperand(T, i), &ISelKilled);\n";
Evan Cheng775baac2007-09-12 23:30:14 +00002037 OS << " } else {\n";
2038 OS << " CurDAG->ReplaceAllUsesWith(F, T, &ISelKilled);\n";
2039 OS << " }\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002040 OS << " setSelected(F->getNodeId());\n";
2041 OS << " RemoveKilled();\n";
2042 OS << "}\n\n";
2043
2044 OS << "// SelectRoot - Top level entry to DAG isel.\n";
2045 OS << "SDOperand SelectRoot(SDOperand Root) {\n";
2046 OS << " SelectRootInit();\n";
2047 OS << " unsigned NumBytes = (DAGSize + 7) / 8;\n";
2048 OS << " ISelQueued = new unsigned char[NumBytes];\n";
2049 OS << " ISelSelected = new unsigned char[NumBytes];\n";
2050 OS << " memset(ISelQueued, 0, NumBytes);\n";
2051 OS << " memset(ISelSelected, 0, NumBytes);\n";
2052 OS << "\n";
2053 OS << " // Create a dummy node (which is not added to allnodes), that adds\n"
2054 << " // a reference to the root node, preventing it from being deleted,\n"
2055 << " // and tracking any changes of the root.\n"
2056 << " HandleSDNode Dummy(CurDAG->getRoot());\n"
2057 << " ISelQueue.push_back(CurDAG->getRoot().Val);\n";
2058 OS << " while (!ISelQueue.empty()) {\n";
2059 OS << " SDNode *Node = ISelQueue.front();\n";
2060 OS << " std::pop_heap(ISelQueue.begin(), ISelQueue.end(), isel_sort());\n";
2061 OS << " ISelQueue.pop_back();\n";
2062 OS << " if (!isSelected(Node->getNodeId())) {\n";
2063 OS << " SDNode *ResNode = Select(SDOperand(Node, 0));\n";
2064 OS << " if (ResNode != Node) {\n";
2065 OS << " if (ResNode)\n";
2066 OS << " ReplaceUses(Node, ResNode);\n";
2067 OS << " if (Node->use_empty()) { // Don't delete EntryToken, etc.\n";
2068 OS << " CurDAG->RemoveDeadNode(Node, ISelKilled);\n";
2069 OS << " RemoveKilled();\n";
2070 OS << " }\n";
2071 OS << " }\n";
2072 OS << " }\n";
2073 OS << " }\n";
2074 OS << "\n";
2075 OS << " delete[] ISelQueued;\n";
2076 OS << " ISelQueued = NULL;\n";
2077 OS << " delete[] ISelSelected;\n";
2078 OS << " ISelSelected = NULL;\n";
2079 OS << " return Dummy.getValue();\n";
2080 OS << "}\n";
2081
Chris Lattner227da452008-01-05 22:54:53 +00002082 EmitNodeTransforms(OS);
Chris Lattner7fdd9342008-01-05 22:43:57 +00002083 EmitPredicateFunctions(OS);
2084
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002085 DOUT << "\n\nALL PATTERNS TO MATCH:\n\n";
Chris Lattnerae506702008-01-06 01:10:31 +00002086 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00002087 I != E; ++I) {
2088 DOUT << "PATTERN: "; DEBUG(I->getSrcPattern()->dump());
2089 DOUT << "\nRESULT: "; DEBUG(I->getDstPattern()->dump());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002090 DOUT << "\n";
2091 }
2092
2093 // At this point, we have full information about the 'Patterns' we need to
2094 // parse, both implicitly from instructions as well as from explicit pattern
2095 // definitions. Emit the resultant instruction selector.
2096 EmitInstructionSelector(OS);
2097
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002098}