blob: 8774c5296524a1210554c3766c08cfcec8632880 [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"
Chris Lattnere7d6e3c2010-02-15 08:04:42 +000015#include "DAGISelMatcher.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000016#include "Record.h"
17#include "llvm/ADT/StringExtras.h"
David Greene932618b2008-10-27 21:56:29 +000018#include "llvm/Support/CommandLine.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Support/Debug.h"
20#include "llvm/Support/MathExtras.h"
David Greene932618b2008-10-27 21:56:29 +000021#include "llvm/Support/Debug.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include <algorithm>
Dan Gohman6761ff52008-07-07 21:00:17 +000023#include <deque>
Daniel Dunbard4287062009-07-03 00:10:29 +000024#include <iostream>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000025using namespace llvm;
26
Chris Lattnerba021ea2009-08-07 22:27:19 +000027static cl::opt<bool>
28GenDebug("gen-debug", cl::desc("Generate debug code"), cl::init(false));
David Greene932618b2008-10-27 21:56:29 +000029
Dan Gohmanf17a25c2007-07-18 16:29:46 +000030//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +000031// DAGISelEmitter Helper methods
Dan Gohmanf17a25c2007-07-18 16:29:46 +000032//
33
Dan Gohman5f082a72010-01-05 01:24:18 +000034/// getNodeName - The top level Select_* functions have an "SDNode* N"
35/// argument. When expanding the pattern-matching code, the intermediate
36/// variables have type SDValue. This function provides a uniform way to
37/// reference the underlying "SDNode *" for both cases.
38static std::string getNodeName(const std::string &S) {
39 if (S == "N") return S;
40 return S + ".getNode()";
41}
42
43/// getNodeValue - Similar to getNodeName, except it provides a uniform
44/// way to access the SDValue for both cases.
45static std::string getValueName(const std::string &S) {
46 if (S == "N") return "SDValue(N, 0)";
47 return S;
48}
49
Chris Lattner4ca8ff02008-01-05 22:25:12 +000050/// NodeIsComplexPattern - return true if N is a leaf node and a subclass of
51/// ComplexPattern.
52static bool NodeIsComplexPattern(TreePatternNode *N) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000053 return (N->isLeaf() &&
54 dynamic_cast<DefInit*>(N->getLeafValue()) &&
55 static_cast<DefInit*>(N->getLeafValue())->getDef()->
56 isSubClassOf("ComplexPattern"));
57}
58
Dan Gohmanf17a25c2007-07-18 16:29:46 +000059
60/// getPatternSize - Return the 'size' of this pattern. We want to match large
61/// patterns before small ones. This is used to determine the size of a
62/// pattern.
Chris Lattnerae506702008-01-06 01:10:31 +000063static unsigned getPatternSize(TreePatternNode *P, CodeGenDAGPatterns &CGP) {
Owen Andersonac9de032009-08-10 22:56:29 +000064 assert((EEVT::isExtIntegerInVTs(P->getExtTypes()) ||
65 EEVT::isExtFloatingPointInVTs(P->getExtTypes()) ||
Owen Anderson36e3a6e2009-08-11 20:47:22 +000066 P->getExtTypeNum(0) == MVT::isVoid ||
67 P->getExtTypeNum(0) == MVT::Flag ||
68 P->getExtTypeNum(0) == MVT::iPTR ||
69 P->getExtTypeNum(0) == MVT::iPTRAny) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000070 "Not a valid pattern node to size!");
71 unsigned Size = 3; // The node itself.
72 // If the root node is a ConstantSDNode, increases its size.
73 // e.g. (set R32:$dst, 0).
74 if (P->isLeaf() && dynamic_cast<IntInit*>(P->getLeafValue()))
75 Size += 2;
76
77 // FIXME: This is a hack to statically increase the priority of patterns
78 // which maps a sub-dag to a complex pattern. e.g. favors LEA over ADD.
79 // Later we can allow complexity / cost for each pattern to be (optionally)
80 // specified. To get best possible pattern match we'll need to dynamically
81 // calculate the complexity of all patterns a dag can potentially map to.
Chris Lattner5c1eb0c2010-02-14 22:22:58 +000082 const ComplexPattern *AM = P->getComplexPatternInfo(CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000083 if (AM)
84 Size += AM->getNumOperands() * 3;
85
86 // If this node has some predicate function that must match, it adds to the
87 // complexity of this node.
Dan Gohman5394e112008-10-15 06:17:21 +000088 if (!P->getPredicateFns().empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 ++Size;
90
91 // Count children in the count if they are also nodes.
92 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i) {
93 TreePatternNode *Child = P->getChild(i);
Owen Anderson36e3a6e2009-08-11 20:47:22 +000094 if (!Child->isLeaf() && Child->getExtTypeNum(0) != MVT::Other)
Chris Lattner4ca8ff02008-01-05 22:25:12 +000095 Size += getPatternSize(Child, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000096 else if (Child->isLeaf()) {
97 if (dynamic_cast<IntInit*>(Child->getLeafValue()))
98 Size += 5; // Matches a ConstantSDNode (+3) and a specific value (+2).
99 else if (NodeIsComplexPattern(Child))
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000100 Size += getPatternSize(Child, CGP);
Dan Gohman5394e112008-10-15 06:17:21 +0000101 else if (!Child->getPredicateFns().empty())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000102 ++Size;
103 }
104 }
105
106 return Size;
107}
108
109/// getResultPatternCost - Compute the number of instructions for this pattern.
110/// This is a temporary hack. We should really include the instruction
111/// latencies in this calculation.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000112static unsigned getResultPatternCost(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000113 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000114 if (P->isLeaf()) return 0;
115
116 unsigned Cost = 0;
117 Record *Op = P->getOperator();
118 if (Op->isSubClassOf("Instruction")) {
119 Cost++;
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000120 CodeGenInstruction &II = CGP.getTargetInfo().getInstruction(Op->getName());
Dan Gohman30afe012009-10-29 18:10:34 +0000121 if (II.usesCustomInserter)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000122 Cost += 10;
123 }
124 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000125 Cost += getResultPatternCost(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000126 return Cost;
127}
128
129/// getResultPatternCodeSize - Compute the code size of instructions for this
130/// pattern.
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000131static unsigned getResultPatternSize(TreePatternNode *P,
Chris Lattnerae506702008-01-06 01:10:31 +0000132 CodeGenDAGPatterns &CGP) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000133 if (P->isLeaf()) return 0;
134
135 unsigned Cost = 0;
136 Record *Op = P->getOperator();
137 if (Op->isSubClassOf("Instruction")) {
138 Cost += Op->getValueAsInt("CodeSize");
139 }
140 for (unsigned i = 0, e = P->getNumChildren(); i != e; ++i)
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000141 Cost += getResultPatternSize(P->getChild(i), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000142 return Cost;
143}
144
145// PatternSortingPredicate - return true if we prefer to match LHS before RHS.
146// In particular, we want to match maximal patterns first and lowest cost within
147// a particular complexity first.
148struct PatternSortingPredicate {
Chris Lattnerae506702008-01-06 01:10:31 +0000149 PatternSortingPredicate(CodeGenDAGPatterns &cgp) : CGP(cgp) {}
150 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000151
Dan Gohman5394e112008-10-15 06:17:21 +0000152 typedef std::pair<unsigned, std::string> CodeLine;
153 typedef std::vector<CodeLine> CodeList;
154 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
155
156 bool operator()(const std::pair<const PatternToMatch*, CodeList> &LHSPair,
157 const std::pair<const PatternToMatch*, CodeList> &RHSPair) {
158 const PatternToMatch *LHS = LHSPair.first;
159 const PatternToMatch *RHS = RHSPair.first;
160
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000161 unsigned LHSSize = getPatternSize(LHS->getSrcPattern(), CGP);
162 unsigned RHSSize = getPatternSize(RHS->getSrcPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000163 LHSSize += LHS->getAddedComplexity();
164 RHSSize += RHS->getAddedComplexity();
165 if (LHSSize > RHSSize) return true; // LHS -> bigger -> less cost
166 if (LHSSize < RHSSize) return false;
167
168 // If the patterns have equal complexity, compare generated instruction cost
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000169 unsigned LHSCost = getResultPatternCost(LHS->getDstPattern(), CGP);
170 unsigned RHSCost = getResultPatternCost(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000171 if (LHSCost < RHSCost) return true;
172 if (LHSCost > RHSCost) return false;
173
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000174 return getResultPatternSize(LHS->getDstPattern(), CGP) <
175 getResultPatternSize(RHS->getDstPattern(), CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 }
177};
178
Jim Grosbach96aa2052009-03-25 23:28:33 +0000179/// getRegisterValueType - Look up and return the ValueType of the specified
180/// register. If the register is a member of multiple register classes which
Owen Anderson36e3a6e2009-08-11 20:47:22 +0000181/// have different associated types, return MVT::Other.
182static MVT::SimpleValueType getRegisterValueType(Record *R, const CodeGenTarget &T) {
Jim Grosbach714bf322009-03-26 14:45:34 +0000183 bool FoundRC = false;
Owen Anderson36e3a6e2009-08-11 20:47:22 +0000184 MVT::SimpleValueType VT = MVT::Other;
Jim Grosbach96aa2052009-03-25 23:28:33 +0000185 const std::vector<CodeGenRegisterClass> &RCs = T.getRegisterClasses();
186 std::vector<CodeGenRegisterClass>::const_iterator RC;
187 std::vector<Record*>::const_iterator Element;
188
189 for (RC = RCs.begin() ; RC != RCs.end() ; RC++) {
190 Element = find((*RC).Elements.begin(), (*RC).Elements.end(), R);
191 if (Element != (*RC).Elements.end()) {
192 if (!FoundRC) {
Jim Grosbach714bf322009-03-26 14:45:34 +0000193 FoundRC = true;
Jim Grosbach96aa2052009-03-25 23:28:33 +0000194 VT = (*RC).getValueTypeNum(0);
195 } else {
196 // In multiple RC's
197 if (VT != (*RC).getValueTypeNum(0)) {
Owen Anderson36e3a6e2009-08-11 20:47:22 +0000198 // Types of the RC's do not agree. Return MVT::Other. The
Jim Grosbach96aa2052009-03-25 23:28:33 +0000199 // target is responsible for handling this.
Owen Anderson36e3a6e2009-08-11 20:47:22 +0000200 return MVT::Other;
Jim Grosbach96aa2052009-03-25 23:28:33 +0000201 }
202 }
203 }
204 }
205 return VT;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000206}
207
Evan Cheng43f0c652008-07-03 08:39:51 +0000208static std::string getOpcodeName(Record *Op, CodeGenDAGPatterns &CGP) {
209 return CGP.getSDNodeInfo(Op).getEnumName();
210}
211
Chris Lattner7fdd9342008-01-05 22:43:57 +0000212//===----------------------------------------------------------------------===//
Chris Lattner227da452008-01-05 22:54:53 +0000213// Node Transformation emitter implementation.
214//
Daniel Dunbard4287062009-07-03 00:10:29 +0000215void DAGISelEmitter::EmitNodeTransforms(raw_ostream &OS) {
Chris Lattner227da452008-01-05 22:54:53 +0000216 // Walk the pattern fragments, adding them to a map, which sorts them by
217 // name.
Chris Lattnerae506702008-01-06 01:10:31 +0000218 typedef std::map<std::string, CodeGenDAGPatterns::NodeXForm> NXsByNameTy;
Chris Lattner227da452008-01-05 22:54:53 +0000219 NXsByNameTy NXsByName;
220
Chris Lattnerae506702008-01-06 01:10:31 +0000221 for (CodeGenDAGPatterns::nx_iterator I = CGP.nx_begin(), E = CGP.nx_end();
Chris Lattner227da452008-01-05 22:54:53 +0000222 I != E; ++I)
223 NXsByName.insert(std::make_pair(I->first->getName(), I->second));
224
225 OS << "\n// Node transformations.\n";
226
227 for (NXsByNameTy::iterator I = NXsByName.begin(), E = NXsByName.end();
228 I != E; ++I) {
229 Record *SDNode = I->second.first;
230 std::string Code = I->second.second;
231
232 if (Code.empty()) continue; // Empty code? Skip it.
233
Chris Lattner14948ea2008-01-05 22:58:54 +0000234 std::string ClassName = CGP.getSDNodeInfo(SDNode).getSDClassName();
Chris Lattner227da452008-01-05 22:54:53 +0000235 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
236
Dan Gohman8181bd12008-07-27 21:46:04 +0000237 OS << "inline SDValue Transform_" << I->first << "(SDNode *" << C2
Chris Lattner227da452008-01-05 22:54:53 +0000238 << ") {\n";
239 if (ClassName != "SDNode")
240 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
241 OS << Code << "\n}\n";
242 }
243}
244
245//===----------------------------------------------------------------------===//
Chris Lattner7fdd9342008-01-05 22:43:57 +0000246// Predicate emitter implementation.
247//
248
Daniel Dunbard4287062009-07-03 00:10:29 +0000249void DAGISelEmitter::EmitPredicateFunctions(raw_ostream &OS) {
Chris Lattner7fdd9342008-01-05 22:43:57 +0000250 OS << "\n// Predicate functions.\n";
251
252 // Walk the pattern fragments, adding them to a map, which sorts them by
253 // name.
254 typedef std::map<std::string, std::pair<Record*, TreePattern*> > PFsByNameTy;
255 PFsByNameTy PFsByName;
256
Chris Lattnerae506702008-01-06 01:10:31 +0000257 for (CodeGenDAGPatterns::pf_iterator I = CGP.pf_begin(), E = CGP.pf_end();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000258 I != E; ++I)
259 PFsByName.insert(std::make_pair(I->first->getName(), *I));
260
261
262 for (PFsByNameTy::iterator I = PFsByName.begin(), E = PFsByName.end();
263 I != E; ++I) {
264 Record *PatFragRecord = I->second.first;// Record that derives from PatFrag.
265 TreePattern *P = I->second.second;
266
267 // If there is a code init for this fragment, emit the predicate code.
268 std::string Code = PatFragRecord->getValueAsCode("Predicate");
269 if (Code.empty()) continue;
270
271 if (P->getOnlyTree()->isLeaf())
272 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattner5c3601c2010-02-16 07:26:36 +0000273 << "(SDNode *N) const {\n";
Chris Lattner7fdd9342008-01-05 22:43:57 +0000274 else {
275 std::string ClassName =
Chris Lattner14948ea2008-01-05 22:58:54 +0000276 CGP.getSDNodeInfo(P->getOnlyTree()->getOperator()).getSDClassName();
Chris Lattner7fdd9342008-01-05 22:43:57 +0000277 const char *C2 = ClassName == "SDNode" ? "N" : "inN";
278
279 OS << "inline bool Predicate_" << PatFragRecord->getName()
Chris Lattner5c3601c2010-02-16 07:26:36 +0000280 << "(SDNode *" << C2 << ") const {\n";
Chris Lattner7fdd9342008-01-05 22:43:57 +0000281 if (ClassName != "SDNode")
282 OS << " " << ClassName << " *N = cast<" << ClassName << ">(inN);\n";
283 }
284 OS << Code << "\n}\n";
285 }
286
287 OS << "\n\n";
288}
289
290
291//===----------------------------------------------------------------------===//
292// PatternCodeEmitter implementation.
293//
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000294class PatternCodeEmitter {
295private:
Chris Lattnerae506702008-01-06 01:10:31 +0000296 CodeGenDAGPatterns &CGP;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000297
298 // Predicates.
Dan Gohmane97f1a32008-08-22 00:20:26 +0000299 std::string PredicateCheck;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000300 // Pattern cost.
301 unsigned Cost;
302 // Instruction selector pattern.
303 TreePatternNode *Pattern;
304 // Matched instruction.
305 TreePatternNode *Instruction;
306
307 // Node to name mapping
308 std::map<std::string, std::string> VariableMap;
309 // Node to operator mapping
310 std::map<std::string, Record*> OperatorMap;
Evan Cheng07f307d2008-02-05 22:50:29 +0000311 // Name of the folded node which produces a flag.
312 std::pair<std::string, unsigned> FoldedFlag;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313 // Names of all the folded nodes which produce chains.
314 std::vector<std::pair<std::string, unsigned> > FoldedChains;
315 // Original input chain(s).
316 std::vector<std::pair<std::string, std::string> > OrigChains;
317 std::set<std::string> Duplicates;
318
Dan Gohman12a9c082008-02-06 22:27:42 +0000319 /// LSI - Load/Store information.
320 /// Save loads/stores matched by a pattern, and generate a MemOperandSDNode
321 /// for each memory access. This facilitates the use of AliasAnalysis in
322 /// the backend.
323 std::vector<std::string> LSI;
324
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000325 /// GeneratedCode - This is the buffer that we emit code to. The first int
326 /// indicates whether this is an exit predicate (something that should be
327 /// tested, and if true, the match fails) [when 1], or normal code to emit
328 /// [when 0], or initialization code to emit [when 2].
329 std::vector<std::pair<unsigned, std::string> > &GeneratedCode;
Dan Gohman8181bd12008-07-27 21:46:04 +0000330 /// GeneratedDecl - This is the set of all SDValue declarations needed for
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000331 /// the set of patterns for each top-level opcode.
332 std::set<std::string> &GeneratedDecl;
333 /// TargetOpcodes - The target specific opcodes used by the resulting
334 /// instructions.
335 std::vector<std::string> &TargetOpcodes;
336 std::vector<std::string> &TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000337 /// OutputIsVariadic - Records whether the instruction output pattern uses
338 /// variable_ops. This requires that the Emit function be passed an
339 /// additional argument to indicate where the input varargs operands
340 /// begin.
341 bool &OutputIsVariadic;
342 /// NumInputRootOps - Records the number of operands the root node of the
343 /// input pattern has. This information is used in the generated code to
344 /// pass to Emit functions when variable_ops processing is needed.
345 unsigned &NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346
347 std::string ChainName;
348 unsigned TmpNo;
349 unsigned OpcNo;
350 unsigned VTNo;
351
352 void emitCheck(const std::string &S) {
353 if (!S.empty())
354 GeneratedCode.push_back(std::make_pair(1, S));
355 }
356 void emitCode(const std::string &S) {
357 if (!S.empty())
358 GeneratedCode.push_back(std::make_pair(0, S));
359 }
360 void emitInit(const std::string &S) {
361 if (!S.empty())
362 GeneratedCode.push_back(std::make_pair(2, S));
363 }
364 void emitDecl(const std::string &S) {
365 assert(!S.empty() && "Invalid declaration");
366 GeneratedDecl.insert(S);
367 }
368 void emitOpcode(const std::string &Opc) {
369 TargetOpcodes.push_back(Opc);
370 OpcNo++;
371 }
372 void emitVT(const std::string &VT) {
373 TargetVTs.push_back(VT);
374 VTNo++;
375 }
376public:
Dan Gohmane97f1a32008-08-22 00:20:26 +0000377 PatternCodeEmitter(CodeGenDAGPatterns &cgp, std::string predcheck,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000378 TreePatternNode *pattern, TreePatternNode *instr,
379 std::vector<std::pair<unsigned, std::string> > &gc,
380 std::set<std::string> &gd,
381 std::vector<std::string> &to,
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000382 std::vector<std::string> &tv,
383 bool &oiv,
384 unsigned &niro)
Dan Gohmane97f1a32008-08-22 00:20:26 +0000385 : CGP(cgp), PredicateCheck(predcheck), Pattern(pattern), Instruction(instr),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 GeneratedCode(gc), GeneratedDecl(gd),
387 TargetOpcodes(to), TargetVTs(tv),
Dan Gohman2c4be2a2008-05-31 02:11:25 +0000388 OutputIsVariadic(oiv), NumInputRootOps(niro),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000389 TmpNo(0), OpcNo(0), VTNo(0) {}
390
391 /// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
392 /// if the match fails. At this point, we already know that the opcode for N
393 /// matches, and the SDNode for the result has the RootName specified name.
394 void EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
395 const std::string &RootName, const std::string &ChainSuffix,
Chris Lattner34c50c22010-02-13 20:06:50 +0000396 bool &FoundChain);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000397
398 void EmitChildMatchCode(TreePatternNode *Child, TreePatternNode *Parent,
Christopher Lamb059c7c92008-01-31 07:27:46 +0000399 const std::string &RootName,
Chris Lattner34c50c22010-02-13 20:06:50 +0000400 const std::string &ChainSuffix, bool &FoundChain);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401
402 /// EmitResultCode - Emit the action for a pattern. Now that it has matched
403 /// we actually have to build a DAG!
404 std::vector<std::string>
Evan Cheng775baac2007-09-12 23:30:14 +0000405 EmitResultCode(TreePatternNode *N, std::vector<Record*> DstRegs,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000406 bool InFlagDecled, bool ResNodeDecled,
Chris Lattner34c50c22010-02-13 20:06:50 +0000407 bool LikeLeaf = false, bool isRoot = false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408
409 /// InsertOneTypeCheck - Insert a type-check for an unresolved type in 'Pat'
410 /// and add it to the tree. 'Pat' and 'Other' are isomorphic trees except that
411 /// 'Pat' may be missing types. If we find an unresolved type to add a check
412 /// for, this returns true otherwise false if Pat has all types.
413 bool InsertOneTypeCheck(TreePatternNode *Pat, TreePatternNode *Other,
414 const std::string &Prefix, bool isRoot = false) {
415 // Did we find one?
416 if (Pat->getExtTypes() != Other->getExtTypes()) {
417 // Move a type over from 'other' to 'pat'.
418 Pat->setTypes(Other->getExtTypes());
419 // The top level node type is checked outside of the select function.
420 if (!isRoot)
Anton Korobeynikove9439102009-11-08 12:14:54 +0000421 emitCheck(Prefix + ".getValueType() == " +
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000422 getName(Pat->getTypeNum(0)));
423 return true;
424 }
425
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000426 unsigned OpNo = (unsigned)Pat->NodeHasProperty(SDNPHasChain, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000427 for (unsigned i = 0, e = Pat->getNumChildren(); i != e; ++i, ++OpNo)
428 if (InsertOneTypeCheck(Pat->getChild(i), Other->getChild(i),
429 Prefix + utostr(OpNo)))
430 return true;
431 return false;
432 }
433
434private:
435 /// EmitInFlagSelectCode - Emit the flag operands for the DAG that is
436 /// being built.
437 void EmitInFlagSelectCode(TreePatternNode *N, const std::string &RootName,
438 bool &ChainEmitted, bool &InFlagDecled,
439 bool &ResNodeDecled, bool isRoot = false) {
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000440 const CodeGenTarget &T = CGP.getTargetInfo();
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000441 unsigned OpNo = (unsigned)N->NodeHasProperty(SDNPHasChain, CGP);
442 bool HasInFlag = N->NodeHasProperty(SDNPInFlag, CGP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000443 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
444 TreePatternNode *Child = N->getChild(i);
445 if (!Child->isLeaf()) {
446 EmitInFlagSelectCode(Child, RootName + utostr(OpNo), ChainEmitted,
447 InFlagDecled, ResNodeDecled);
448 } else {
449 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
450 if (!Child->getName().empty()) {
451 std::string Name = RootName + utostr(OpNo);
452 if (Duplicates.find(Name) != Duplicates.end())
453 // A duplicate! Do not emit a copy for this node.
454 continue;
455 }
456
457 Record *RR = DI->getDef();
458 if (RR->isSubClassOf("Register")) {
Owen Anderson36e3a6e2009-08-11 20:47:22 +0000459 MVT::SimpleValueType RVT = getRegisterValueType(RR, T);
460 if (RVT == MVT::Flag) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000461 if (!InFlagDecled) {
Dan Gohman5f082a72010-01-05 01:24:18 +0000462 emitCode("SDValue InFlag = " +
463 getValueName(RootName + utostr(OpNo)) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 InFlagDecled = true;
465 } else
Dan Gohman5f082a72010-01-05 01:24:18 +0000466 emitCode("InFlag = " +
467 getValueName(RootName + utostr(OpNo)) + ";");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000468 } else {
469 if (!ChainEmitted) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000470 emitCode("SDValue Chain = CurDAG->getEntryNode();");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000471 ChainName = "Chain";
472 ChainEmitted = true;
473 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000474 if (!InFlagDecled) {
Dan Gohman8181bd12008-07-27 21:46:04 +0000475 emitCode("SDValue InFlag(0, 0);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000476 InFlagDecled = true;
477 }
Dale Johannesen747fe522009-06-02 03:12:52 +0000478 std::string Decl = (!ResNodeDecled) ? "SDNode *" : "";
479 emitCode(Decl + "ResNode = CurDAG->getCopyToReg(" + ChainName +
Dan Gohman5f082a72010-01-05 01:24:18 +0000480 ", " + getNodeName(RootName) + "->getDebugLoc()" +
Chris Lattner4ca8ff02008-01-05 22:25:12 +0000481 ", " + getQualifiedName(RR) +
Dan Gohman5f082a72010-01-05 01:24:18 +0000482 ", " + getValueName(RootName + utostr(OpNo)) +
483 ", InFlag).getNode();");
Dale Johannesen747fe522009-06-02 03:12:52 +0000484 ResNodeDecled = true;
Dan Gohman8181bd12008-07-27 21:46:04 +0000485 emitCode(ChainName + " = SDValue(ResNode, 0);");
486 emitCode("InFlag = SDValue(ResNode, 1);");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000487 }
488 }
489 }
490 }
491 }
492
Dale Johannesen747fe522009-06-02 03:12:52 +0000493 if (HasInFlag) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000494 if (!InFlagDecled) {
Dan Gohman5f082a72010-01-05 01:24:18 +0000495 emitCode("SDValue InFlag = " + getNodeName(RootName) +
496 "->getOperand(" + utostr(OpNo) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 InFlagDecled = true;
498 } else
Dan Gohman5f082a72010-01-05 01:24:18 +0000499 emitCode("InFlag = " + getNodeName(RootName) +
500 "->getOperand(" + utostr(OpNo) + ");");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000501 }
502 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503};
504
Chris Lattner34c50c22010-02-13 20:06:50 +0000505
506/// EmitMatchCode - Emit a matcher for N, going to the label for PatternNo
507/// if the match fails. At this point, we already know that the opcode for N
508/// matches, and the SDNode for the result has the RootName specified name.
509void PatternCodeEmitter::EmitMatchCode(TreePatternNode *N, TreePatternNode *P,
510 const std::string &RootName,
511 const std::string &ChainSuffix,
512 bool &FoundChain) {
Chris Lattner34c50c22010-02-13 20:06:50 +0000513 // Save loads/stores matched by a pattern.
514 if (!N->isLeaf() && N->getName().empty()) {
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000515 if (N->NodeHasProperty(SDNPMemOperand, CGP))
Chris Lattner34c50c22010-02-13 20:06:50 +0000516 LSI.push_back(getNodeName(RootName));
517 }
518
519 bool isRoot = (P == NULL);
520 // Emit instruction predicates. Each predicate is just a string for now.
521 if (isRoot) {
522 // Record input varargs info.
523 NumInputRootOps = N->getNumChildren();
Chris Lattner34c50c22010-02-13 20:06:50 +0000524 emitCheck(PredicateCheck);
525 }
526
527 if (N->isLeaf()) {
528 if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
529 emitCheck("cast<ConstantSDNode>(" + getNodeName(RootName) +
530 ")->getSExtValue() == INT64_C(" +
531 itostr(II->getValue()) + ")");
532 return;
533 } else if (!NodeIsComplexPattern(N)) {
534 assert(0 && "Cannot match this as a leaf value!");
535 abort();
536 }
537 }
538
539 // If this node has a name associated with it, capture it in VariableMap. If
540 // we already saw this in the pattern, emit code to verify dagness.
541 if (!N->getName().empty()) {
542 std::string &VarMapEntry = VariableMap[N->getName()];
543 if (VarMapEntry.empty()) {
544 VarMapEntry = RootName;
545 } else {
546 // If we get here, this is a second reference to a specific name. Since
547 // we already have checked that the first reference is valid, we don't
548 // have to recursively match it, just check that it's the same as the
549 // previously named thing.
550 emitCheck(VarMapEntry + " == " + RootName);
551 return;
552 }
553
554 if (!N->isLeaf())
555 OperatorMap[N->getName()] = N->getOperator();
556 }
557
558
559 // Emit code to load the child nodes and match their contents recursively.
560 unsigned OpNo = 0;
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000561 bool NodeHasChain = N->NodeHasProperty(SDNPHasChain, CGP);
562 bool HasChain = N->TreeHasProperty(SDNPHasChain, CGP);
Chris Lattner34c50c22010-02-13 20:06:50 +0000563 if (HasChain) {
564 if (NodeHasChain)
565 OpNo = 1;
566 if (!isRoot) {
Evan Chengf80681e2010-02-15 19:41:07 +0000567 // Check if it's profitable to fold the node. e.g. Check for multiple uses
568 // of actual result?
569 std::string ParentName(RootName.begin(), RootName.end()-1);
Chris Lattner54d5c5b2010-02-16 19:03:34 +0000570 if (!NodeHasChain) {
571 // If this is just an interior node, check to see if it has a single
572 // use. If the node has multiple uses and the pattern has a load as
573 // an operand, then we can't fold the load.
574 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattnerecbbf492010-02-16 22:35:06 +0000575 } else if (!N->isLeaf()) { // ComplexPatterns do their own legality check.
Chris Lattner34c50c22010-02-13 20:06:50 +0000576 // If the immediate use can somehow reach this node through another
577 // path, then can't fold it either or it will create a cycle.
578 // e.g. In the following diagram, XX can reach ld through YY. If
579 // ld is folded into XX, then YY is both a predecessor and a successor
580 // of XX.
581 //
582 // [ld]
583 // ^ ^
584 // | |
585 // / \---
586 // / [YY]
587 // | ^
588 // [XX]-------|
Chris Lattner9de39482010-02-16 06:10:58 +0000589
590 // We know we need the check if N's parent is not the root.
Chris Lattner34c50c22010-02-13 20:06:50 +0000591 bool NeedCheck = P != Pattern;
592 if (!NeedCheck) {
Chris Lattner54d5c5b2010-02-16 19:03:34 +0000593 // If the parent is the root and the node has more than one operand,
594 // we need to check.
Chris Lattner34c50c22010-02-13 20:06:50 +0000595 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(P->getOperator());
596 NeedCheck =
597 P->getOperator() == CGP.get_intrinsic_void_sdnode() ||
598 P->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
599 P->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
600 PInfo.getNumOperands() > 1 ||
601 PInfo.hasProperty(SDNPHasChain) ||
602 PInfo.hasProperty(SDNPInFlag) ||
603 PInfo.hasProperty(SDNPOptInFlag);
604 }
605
606 if (NeedCheck) {
Chris Lattner54d5c5b2010-02-16 19:03:34 +0000607 emitCheck("IsProfitableToFold(" + getValueName(RootName) +
608 ", " + getNodeName(ParentName) + ", N)");
Evan Chengf80681e2010-02-15 19:41:07 +0000609 emitCheck("IsLegalToFold(" + getValueName(RootName) +
Chris Lattner34c50c22010-02-13 20:06:50 +0000610 ", " + getNodeName(ParentName) + ", N)");
Chris Lattner54d5c5b2010-02-16 19:03:34 +0000611 } else {
612 // Otherwise, just verify that the node only has a single use.
613 emitCheck(getValueName(RootName) + ".hasOneUse()");
Chris Lattner34c50c22010-02-13 20:06:50 +0000614 }
615 }
616 }
617
618 if (NodeHasChain) {
619 if (FoundChain) {
620 emitCheck("(" + ChainName + ".getNode() == " +
621 getNodeName(RootName) + " || "
622 "IsChainCompatible(" + ChainName + ".getNode(), " +
623 getNodeName(RootName) + "))");
624 OrigChains.push_back(std::make_pair(ChainName,
625 getValueName(RootName)));
626 } else
627 FoundChain = true;
628 ChainName = "Chain" + ChainSuffix;
Chris Lattnerecbbf492010-02-16 22:35:06 +0000629
630 if (!N->getComplexPatternInfo(CGP) ||
631 isRoot)
632 emitInit("SDValue " + ChainName + " = " + getNodeName(RootName) +
633 "->getOperand(0);");
Chris Lattner34c50c22010-02-13 20:06:50 +0000634 }
635 }
636
Chris Lattner34c50c22010-02-13 20:06:50 +0000637 // If there are node predicates for this, emit the calls.
638 for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
639 emitCheck(N->getPredicateFns()[i] + "(" + getNodeName(RootName) + ")");
640
641 // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
642 // a constant without a predicate fn that has more that one bit set, handle
643 // this as a special case. This is usually for targets that have special
644 // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
645 // handling stuff). Using these instructions is often far more efficient
646 // than materializing the constant. Unfortunately, both the instcombiner
647 // and the dag combiner can often infer that bits are dead, and thus drop
648 // them from the mask in the dag. For example, it might turn 'AND X, 255'
649 // into 'AND X, 254' if it knows the low bit is set. Emit code that checks
650 // to handle this.
651 if (!N->isLeaf() &&
652 (N->getOperator()->getName() == "and" ||
653 N->getOperator()->getName() == "or") &&
654 N->getChild(1)->isLeaf() &&
655 N->getChild(1)->getPredicateFns().empty()) {
656 if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
657 if (!isPowerOf2_32(II->getValue())) { // Don't bother with single bits.
658 emitInit("SDValue " + RootName + "0" + " = " +
659 getNodeName(RootName) + "->getOperand(" + utostr(0) + ");");
660 emitInit("SDValue " + RootName + "1" + " = " +
661 getNodeName(RootName) + "->getOperand(" + utostr(1) + ");");
662
663 unsigned NTmp = TmpNo++;
664 emitCode("ConstantSDNode *Tmp" + utostr(NTmp) +
665 " = dyn_cast<ConstantSDNode>(" +
666 getNodeName(RootName + "1") + ");");
667 emitCheck("Tmp" + utostr(NTmp));
668 const char *MaskPredicate = N->getOperator()->getName() == "or"
669 ? "CheckOrMask(" : "CheckAndMask(";
670 emitCheck(MaskPredicate + getValueName(RootName + "0") +
671 ", Tmp" + utostr(NTmp) +
672 ", INT64_C(" + itostr(II->getValue()) + "))");
673
674 EmitChildMatchCode(N->getChild(0), N, RootName + utostr(0),
675 ChainSuffix + utostr(0), FoundChain);
676 return;
677 }
678 }
679 }
680
681 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
682 emitInit("SDValue " + getValueName(RootName + utostr(OpNo)) + " = " +
683 getNodeName(RootName) + "->getOperand(" + utostr(OpNo) + ");");
684
685 EmitChildMatchCode(N->getChild(i), N, RootName + utostr(OpNo),
686 ChainSuffix + utostr(OpNo), FoundChain);
687 }
688
689 // Handle cases when root is a complex pattern.
690 const ComplexPattern *CP;
Chris Lattnerecbbf492010-02-16 22:35:06 +0000691 if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
Chris Lattner34c50c22010-02-13 20:06:50 +0000692 std::string Fn = CP->getSelectFunc();
693 unsigned NumOps = CP->getNumOperands();
694 for (unsigned i = 0; i < NumOps; ++i) {
695 emitDecl("CPTmp" + RootName + "_" + utostr(i));
696 emitCode("SDValue CPTmp" + RootName + "_" + utostr(i) + ";");
697 }
698 if (CP->hasProperty(SDNPHasChain)) {
699 emitDecl("CPInChain");
700 emitDecl("Chain" + ChainSuffix);
701 emitCode("SDValue CPInChain;");
702 emitCode("SDValue Chain" + ChainSuffix + ";");
703 }
704
Chris Lattnerecbbf492010-02-16 22:35:06 +0000705 std::string Code = Fn + "(N, "; // always pass in the root.
706 Code += getValueName(RootName);
Chris Lattner34c50c22010-02-13 20:06:50 +0000707 for (unsigned i = 0; i < NumOps; i++)
708 Code += ", CPTmp" + RootName + "_" + utostr(i);
709 if (CP->hasProperty(SDNPHasChain)) {
710 ChainName = "Chain" + ChainSuffix;
711 Code += ", CPInChain, Chain" + ChainSuffix;
712 }
713 emitCheck(Code + ")");
714 }
715}
716
717void PatternCodeEmitter::EmitChildMatchCode(TreePatternNode *Child,
718 TreePatternNode *Parent,
719 const std::string &RootName,
720 const std::string &ChainSuffix,
721 bool &FoundChain) {
722 if (!Child->isLeaf()) {
723 // If it's not a leaf, recursively match.
724 const SDNodeInfo &CInfo = CGP.getSDNodeInfo(Child->getOperator());
725 emitCheck(getNodeName(RootName) + "->getOpcode() == " +
726 CInfo.getEnumName());
727 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
728 bool HasChain = false;
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000729 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
Chris Lattner34c50c22010-02-13 20:06:50 +0000730 HasChain = true;
731 FoldedChains.push_back(std::make_pair(getValueName(RootName),
732 CInfo.getNumResults()));
733 }
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000734 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
Chris Lattner34c50c22010-02-13 20:06:50 +0000735 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
736 "Pattern folded multiple nodes which produce flags?");
737 FoldedFlag = std::make_pair(getValueName(RootName),
738 CInfo.getNumResults() + (unsigned)HasChain);
739 }
Chris Lattnerecbbf492010-02-16 22:35:06 +0000740 } else if (const ComplexPattern *CP = Child->getComplexPatternInfo(CGP)) {
741 if (CP->getSelectFunc() == "SelectScalarSSELoad")
742 errs() << "FOUND IT\n";
743 EmitMatchCode(Child, Parent, RootName, ChainSuffix, FoundChain);
744 bool HasChain = false;
745
746 if (Child->NodeHasProperty(SDNPHasChain, CGP)) {
747 HasChain = true;
748 const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Parent->getOperator());
749 FoldedChains.push_back(std::make_pair("CPInChain",
750 PInfo.getNumResults()));
751 }
752 if (Child->NodeHasProperty(SDNPOutFlag, CGP)) {
753 assert(FoldedFlag.first == "" && FoldedFlag.second == 0 &&
754 "Pattern folded multiple nodes which produce flags?");
755 FoldedFlag = std::make_pair(getValueName(RootName),
756 CP->getNumOperands() + (unsigned)HasChain);
757 }
Chris Lattner34c50c22010-02-13 20:06:50 +0000758 } else {
759 // If this child has a name associated with it, capture it in VarMap. If
760 // we already saw this in the pattern, emit code to verify dagness.
761 if (!Child->getName().empty()) {
762 std::string &VarMapEntry = VariableMap[Child->getName()];
763 if (VarMapEntry.empty()) {
764 VarMapEntry = getValueName(RootName);
765 } else {
766 // If we get here, this is a second reference to a specific name.
767 // Since we already have checked that the first reference is valid,
768 // we don't have to recursively match it, just check that it's the
769 // same as the previously named thing.
770 emitCheck(VarMapEntry + " == " + getValueName(RootName));
771 Duplicates.insert(getValueName(RootName));
772 return;
773 }
774 }
775
776 // Handle leaves of various types.
777 if (DefInit *DI = dynamic_cast<DefInit*>(Child->getLeafValue())) {
778 Record *LeafRec = DI->getDef();
779 if (LeafRec->isSubClassOf("RegisterClass") ||
780 LeafRec->isSubClassOf("PointerLikeRegClass")) {
781 // Handle register references. Nothing to do here.
782 } else if (LeafRec->isSubClassOf("Register")) {
783 // Handle register references.
Chris Lattner34c50c22010-02-13 20:06:50 +0000784 } else if (LeafRec->getName() == "srcvalue") {
785 // Place holder for SRCVALUE nodes. Nothing to do here.
786 } else if (LeafRec->isSubClassOf("ValueType")) {
787 // Make sure this is the specified value type.
788 emitCheck("cast<VTSDNode>(" + getNodeName(RootName) +
789 ")->getVT() == MVT::" + LeafRec->getName());
790 } else if (LeafRec->isSubClassOf("CondCode")) {
791 // Make sure this is the specified cond code.
792 emitCheck("cast<CondCodeSDNode>(" + getNodeName(RootName) +
793 ")->get() == ISD::" + LeafRec->getName());
794 } else {
795#ifndef NDEBUG
796 Child->dump();
797 errs() << " ";
798#endif
799 assert(0 && "Unknown leaf type!");
800 }
801
802 // If there are node predicates for this, emit the calls.
803 for (unsigned i = 0, e = Child->getPredicateFns().size(); i != e; ++i)
804 emitCheck(Child->getPredicateFns()[i] + "(" + getNodeName(RootName) +
805 ")");
806 } else if (IntInit *II =
807 dynamic_cast<IntInit*>(Child->getLeafValue())) {
808 unsigned NTmp = TmpNo++;
809 emitCode("ConstantSDNode *Tmp"+ utostr(NTmp) +
810 " = dyn_cast<ConstantSDNode>("+
811 getNodeName(RootName) + ");");
812 emitCheck("Tmp" + utostr(NTmp));
813 unsigned CTmp = TmpNo++;
814 emitCode("int64_t CN"+ utostr(CTmp) +
815 " = Tmp" + utostr(NTmp) + "->getSExtValue();");
816 emitCheck("CN" + utostr(CTmp) + " == "
817 "INT64_C(" +itostr(II->getValue()) + ")");
818 } else {
819#ifndef NDEBUG
820 Child->dump();
821#endif
822 assert(0 && "Unknown leaf type!");
823 }
824 }
825}
826
827/// EmitResultCode - Emit the action for a pattern. Now that it has matched
828/// we actually have to build a DAG!
829std::vector<std::string>
830PatternCodeEmitter::EmitResultCode(TreePatternNode *N,
831 std::vector<Record*> DstRegs,
832 bool InFlagDecled, bool ResNodeDecled,
833 bool LikeLeaf, bool isRoot) {
834 // List of arguments of getMachineNode() or SelectNodeTo().
835 std::vector<std::string> NodeOps;
836 // This is something selected from the pattern we matched.
837 if (!N->getName().empty()) {
838 const std::string &VarName = N->getName();
839 std::string Val = VariableMap[VarName];
840 bool ModifiedVal = false;
841 if (Val.empty()) {
842 errs() << "Variable '" << VarName << " referenced but not defined "
843 << "and not caught earlier!\n";
844 abort();
845 }
846 if (Val[0] == 'T' && Val[1] == 'm' && Val[2] == 'p') {
847 // Already selected this operand, just return the tmpval.
848 NodeOps.push_back(getValueName(Val));
849 return NodeOps;
850 }
851
852 const ComplexPattern *CP;
853 unsigned ResNo = TmpNo++;
854 if (!N->isLeaf() && N->getOperator()->getName() == "imm") {
855 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
856 std::string CastType;
857 std::string TmpVar = "Tmp" + utostr(ResNo);
858 switch (N->getTypeNum(0)) {
859 default:
860 errs() << "Cannot handle " << getEnumName(N->getTypeNum(0))
861 << " type as an immediate constant. Aborting\n";
862 abort();
863 case MVT::i1: CastType = "bool"; break;
864 case MVT::i8: CastType = "unsigned char"; break;
865 case MVT::i16: CastType = "unsigned short"; break;
866 case MVT::i32: CastType = "unsigned"; break;
867 case MVT::i64: CastType = "uint64_t"; break;
868 }
869 emitCode("SDValue " + TmpVar +
870 " = CurDAG->getTargetConstant(((" + CastType +
871 ") cast<ConstantSDNode>(" + Val + ")->getZExtValue()), " +
872 getEnumName(N->getTypeNum(0)) + ");");
873 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
874 // value if used multiple times by this pattern result.
875 Val = TmpVar;
876 ModifiedVal = true;
877 NodeOps.push_back(getValueName(Val));
878 } else if (!N->isLeaf() && N->getOperator()->getName() == "fpimm") {
879 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
880 std::string TmpVar = "Tmp" + utostr(ResNo);
881 emitCode("SDValue " + TmpVar +
882 " = CurDAG->getTargetConstantFP(*cast<ConstantFPSDNode>(" +
883 Val + ")->getConstantFPValue(), cast<ConstantFPSDNode>(" +
884 Val + ")->getValueType(0));");
885 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select this
886 // value if used multiple times by this pattern result.
887 Val = TmpVar;
888 ModifiedVal = true;
889 NodeOps.push_back(getValueName(Val));
890 } else if (!N->isLeaf() && N->getOperator()->getName() == "texternalsym"){
891 Record *Op = OperatorMap[N->getName()];
892 // Transform ExternalSymbol to TargetExternalSymbol
893 if (Op && Op->getName() == "externalsym") {
894 std::string TmpVar = "Tmp"+utostr(ResNo);
895 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
896 "ExternalSymbol(cast<ExternalSymbolSDNode>(" +
897 Val + ")->getSymbol(), " +
898 getEnumName(N->getTypeNum(0)) + ");");
899 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
900 // this value if used multiple times by this pattern result.
901 Val = TmpVar;
902 ModifiedVal = true;
903 }
904 NodeOps.push_back(getValueName(Val));
905 } else if (!N->isLeaf() && (N->getOperator()->getName() == "tglobaladdr"
906 || N->getOperator()->getName() == "tglobaltlsaddr")) {
907 Record *Op = OperatorMap[N->getName()];
908 // Transform GlobalAddress to TargetGlobalAddress
909 if (Op && (Op->getName() == "globaladdr" ||
910 Op->getName() == "globaltlsaddr")) {
911 std::string TmpVar = "Tmp" + utostr(ResNo);
912 emitCode("SDValue " + TmpVar + " = CurDAG->getTarget"
913 "GlobalAddress(cast<GlobalAddressSDNode>(" + Val +
914 ")->getGlobal(), " + getEnumName(N->getTypeNum(0)) +
915 ");");
916 // Add Tmp<ResNo> to VariableMap, so that we don't multiply select
917 // this value if used multiple times by this pattern result.
918 Val = TmpVar;
919 ModifiedVal = true;
920 }
921 NodeOps.push_back(getValueName(Val));
922 } else if (!N->isLeaf()
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000923 && (N->getOperator()->getName() == "texternalsym" ||
924 N->getOperator()->getName() == "tconstpool")) {
925 // Do not rewrite the variable name, since we don't generate a new
926 // temporary.
927 NodeOps.push_back(getValueName(Val));
928 } else if (N->isLeaf() && (CP = N->getComplexPatternInfo(CGP))) {
929 for (unsigned i = 0; i < CP->getNumOperands(); ++i) {
930 NodeOps.push_back(getValueName("CPTmp" + Val + "_" + utostr(i)));
931 }
932 } else {
933 // This node, probably wrapped in a SDNodeXForm, behaves like a leaf
934 // node even if it isn't one. Don't select it.
935 if (!LikeLeaf) {
936 if (isRoot && N->isLeaf()) {
937 emitCode("ReplaceUses(SDValue(N, 0), " + Val + ");");
938 emitCode("return NULL;");
939 }
940 }
941 NodeOps.push_back(getValueName(Val));
Chris Lattner34c50c22010-02-13 20:06:50 +0000942 }
Chris Lattner5c1eb0c2010-02-14 22:22:58 +0000943
944 if (ModifiedVal)
945 VariableMap[VarName] = Val;
Chris Lattner34c50c22010-02-13 20:06:50 +0000946 return NodeOps;
947 }
948 if (N->isLeaf()) {
949 // If this is an explicit register reference, handle it.
950 if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
951 unsigned ResNo = TmpNo++;
952 if (DI->getDef()->isSubClassOf("Register")) {
953 emitCode("SDValue Tmp" + utostr(ResNo) + " = CurDAG->getRegister(" +
954 getQualifiedName(DI->getDef()) + ", " +
955 getEnumName(N->getTypeNum(0)) + ");");
956 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
957 return NodeOps;
958 } else if (DI->getDef()->getName() == "zero_reg") {
959 emitCode("SDValue Tmp" + utostr(ResNo) +
960 " = CurDAG->getRegister(0, " +
961 getEnumName(N->getTypeNum(0)) + ");");
962 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
963 return NodeOps;
964 } else if (DI->getDef()->isSubClassOf("RegisterClass")) {
965 // Handle a reference to a register class. This is used
966 // in COPY_TO_SUBREG instructions.
967 emitCode("SDValue Tmp" + utostr(ResNo) +
968 " = CurDAG->getTargetConstant(" +
969 getQualifiedName(DI->getDef()) + "RegClassID, " +
970 "MVT::i32);");
971 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
972 return NodeOps;
973 }
974 } else if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
975 unsigned ResNo = TmpNo++;
976 assert(N->getExtTypes().size() == 1 && "Multiple types not handled!");
977 emitCode("SDValue Tmp" + utostr(ResNo) +
978 " = CurDAG->getTargetConstant(0x" +
979 utohexstr((uint64_t) II->getValue()) +
980 "ULL, " + getEnumName(N->getTypeNum(0)) + ");");
981 NodeOps.push_back(getValueName("Tmp" + utostr(ResNo)));
982 return NodeOps;
983 }
984
985#ifndef NDEBUG
986 N->dump();
987#endif
988 assert(0 && "Unknown leaf type!");
989 return NodeOps;
990 }
991
992 Record *Op = N->getOperator();
993 if (Op->isSubClassOf("Instruction")) {
994 const CodeGenTarget &CGT = CGP.getTargetInfo();
995 CodeGenInstruction &II = CGT.getInstruction(Op->getName());
996 const DAGInstruction &Inst = CGP.getInstruction(Op);
997 const TreePattern *InstPat = Inst.getPattern();
998 // FIXME: Assume actual pattern comes before "implicit".
999 TreePatternNode *InstPatNode =
1000 isRoot ? (InstPat ? InstPat->getTree(0) : Pattern)
1001 : (InstPat ? InstPat->getTree(0) : NULL);
1002 if (InstPatNode && !InstPatNode->isLeaf() &&
1003 InstPatNode->getOperator()->getName() == "set") {
1004 InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
1005 }
1006 bool IsVariadic = isRoot && II.isVariadic;
1007 // FIXME: fix how we deal with physical register operands.
1008 bool HasImpInputs = isRoot && Inst.getNumImpOperands() > 0;
1009 bool HasImpResults = isRoot && DstRegs.size() > 0;
1010 bool NodeHasOptInFlag = isRoot &&
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001011 Pattern->TreeHasProperty(SDNPOptInFlag, CGP);
Chris Lattner34c50c22010-02-13 20:06:50 +00001012 bool NodeHasInFlag = isRoot &&
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001013 Pattern->TreeHasProperty(SDNPInFlag, CGP);
Chris Lattner34c50c22010-02-13 20:06:50 +00001014 bool NodeHasOutFlag = isRoot &&
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001015 Pattern->TreeHasProperty(SDNPOutFlag, CGP);
Chris Lattner34c50c22010-02-13 20:06:50 +00001016 bool NodeHasChain = InstPatNode &&
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001017 InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
1018 bool InputHasChain = isRoot && Pattern->NodeHasProperty(SDNPHasChain, CGP);
Chris Lattner34c50c22010-02-13 20:06:50 +00001019 unsigned NumResults = Inst.getNumResults();
1020 unsigned NumDstRegs = HasImpResults ? DstRegs.size() : 0;
1021
1022 // Record output varargs info.
1023 OutputIsVariadic = IsVariadic;
1024
1025 if (NodeHasOptInFlag) {
1026 emitCode("bool HasInFlag = "
1027 "(N->getOperand(N->getNumOperands()-1).getValueType() == "
1028 "MVT::Flag);");
1029 }
1030 if (IsVariadic)
1031 emitCode("SmallVector<SDValue, 8> Ops" + utostr(OpcNo) + ";");
1032
1033 // How many results is this pattern expected to produce?
1034 unsigned NumPatResults = 0;
1035 for (unsigned i = 0, e = Pattern->getExtTypes().size(); i != e; i++) {
1036 MVT::SimpleValueType VT = Pattern->getTypeNum(i);
1037 if (VT != MVT::isVoid && VT != MVT::Flag)
1038 NumPatResults++;
1039 }
1040
1041 if (OrigChains.size() > 0) {
1042 // The original input chain is being ignored. If it is not just
1043 // pointing to the op that's being folded, we should create a
1044 // TokenFactor with it and the chain of the folded op as the new chain.
1045 // We could potentially be doing multiple levels of folding, in that
1046 // case, the TokenFactor can have more operands.
1047 emitCode("SmallVector<SDValue, 8> InChains;");
1048 for (unsigned i = 0, e = OrigChains.size(); i < e; ++i) {
1049 emitCode("if (" + OrigChains[i].first + ".getNode() != " +
1050 OrigChains[i].second + ".getNode()) {");
1051 emitCode(" InChains.push_back(" + OrigChains[i].first + ");");
1052 emitCode("}");
1053 }
1054 emitCode("InChains.push_back(" + ChainName + ");");
1055 emitCode(ChainName + " = CurDAG->getNode(ISD::TokenFactor, "
1056 "N->getDebugLoc(), MVT::Other, "
1057 "&InChains[0], InChains.size());");
1058 if (GenDebug) {
1059 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"yellow\");");
1060 emitCode("CurDAG->setSubgraphColor(" + ChainName +".getNode(), \"black\");");
1061 }
1062 }
1063
1064 // Loop over all of the operands of the instruction pattern, emitting code
1065 // to fill them all in. The node 'N' usually has number children equal to
1066 // the number of input operands of the instruction. However, in cases
1067 // where there are predicate operands for an instruction, we need to fill
1068 // in the 'execute always' values. Match up the node operands to the
1069 // instruction operands to do this.
1070 std::vector<std::string> AllOps;
1071 for (unsigned ChildNo = 0, InstOpNo = NumResults;
1072 InstOpNo != II.OperandList.size(); ++InstOpNo) {
1073 std::vector<std::string> Ops;
1074
1075 // Determine what to emit for this operand.
1076 Record *OperandNode = II.OperandList[InstOpNo].Rec;
1077 if ((OperandNode->isSubClassOf("PredicateOperand") ||
1078 OperandNode->isSubClassOf("OptionalDefOperand")) &&
1079 !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
1080 // This is a predicate or optional def operand; emit the
1081 // 'default ops' operands.
1082 const DAGDefaultOperand &DefaultOp =
1083 CGP.getDefaultOperand(II.OperandList[InstOpNo].Rec);
1084 for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i) {
1085 Ops = EmitResultCode(DefaultOp.DefaultOps[i], DstRegs,
1086 InFlagDecled, ResNodeDecled);
1087 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1088 }
1089 } else {
1090 // Otherwise this is a normal operand or a predicate operand without
1091 // 'execute always'; emit it.
1092 Ops = EmitResultCode(N->getChild(ChildNo), DstRegs,
1093 InFlagDecled, ResNodeDecled);
1094 AllOps.insert(AllOps.end(), Ops.begin(), Ops.end());
1095 ++ChildNo;
1096 }
1097 }
1098
1099 // Emit all the chain and CopyToReg stuff.
1100 bool ChainEmitted = NodeHasChain;
1101 if (NodeHasInFlag || HasImpInputs)
1102 EmitInFlagSelectCode(Pattern, "N", ChainEmitted,
1103 InFlagDecled, ResNodeDecled, true);
1104 if (NodeHasOptInFlag || NodeHasInFlag || HasImpInputs) {
1105 if (!InFlagDecled) {
1106 emitCode("SDValue InFlag(0, 0);");
1107 InFlagDecled = true;
1108 }
1109 if (NodeHasOptInFlag) {
1110 emitCode("if (HasInFlag) {");
1111 emitCode(" InFlag = N->getOperand(N->getNumOperands()-1);");
1112 emitCode("}");
1113 }
1114 }
1115
1116 unsigned ResNo = TmpNo++;
1117
1118 unsigned OpsNo = OpcNo;
1119 std::string CodePrefix;
1120 bool ChainAssignmentNeeded = NodeHasChain && !isRoot;
1121 std::deque<std::string> After;
1122 std::string NodeName;
1123 if (!isRoot) {
1124 NodeName = "Tmp" + utostr(ResNo);
1125 CodePrefix = "SDValue " + NodeName + "(";
1126 } else {
1127 NodeName = "ResNode";
1128 if (!ResNodeDecled) {
1129 CodePrefix = "SDNode *" + NodeName + " = ";
1130 ResNodeDecled = true;
1131 } else
1132 CodePrefix = NodeName + " = ";
1133 }
1134
1135 std::string Code = "Opc" + utostr(OpcNo);
1136
1137 if (!isRoot || (InputHasChain && !NodeHasChain))
1138 // For call to "getMachineNode()".
1139 Code += ", N->getDebugLoc()";
1140
1141 emitOpcode(II.Namespace + "::" + II.TheDef->getName());
1142
1143 // Output order: results, chain, flags
1144 // Result types.
1145 if (NumResults > 0 && N->getTypeNum(0) != MVT::isVoid) {
1146 Code += ", VT" + utostr(VTNo);
1147 emitVT(getEnumName(N->getTypeNum(0)));
1148 }
1149 // Add types for implicit results in physical registers, scheduler will
1150 // care of adding copyfromreg nodes.
1151 for (unsigned i = 0; i < NumDstRegs; i++) {
1152 Record *RR = DstRegs[i];
1153 if (RR->isSubClassOf("Register")) {
1154 MVT::SimpleValueType RVT = getRegisterValueType(RR, CGT);
1155 Code += ", " + getEnumName(RVT);
1156 }
1157 }
1158 if (NodeHasChain)
1159 Code += ", MVT::Other";
1160 if (NodeHasOutFlag)
1161 Code += ", MVT::Flag";
1162
1163 // Inputs.
1164 if (IsVariadic) {
1165 for (unsigned i = 0, e = AllOps.size(); i != e; ++i)
1166 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + AllOps[i] + ");");
1167 AllOps.clear();
1168
1169 // Figure out whether any operands at the end of the op list are not
1170 // part of the variable section.
1171 std::string EndAdjust;
1172 if (NodeHasInFlag || HasImpInputs)
1173 EndAdjust = "-1"; // Always has one flag.
1174 else if (NodeHasOptInFlag)
1175 EndAdjust = "-(HasInFlag?1:0)"; // May have a flag.
1176
1177 emitCode("for (unsigned i = NumInputRootOps + " + utostr(NodeHasChain) +
1178 ", e = N->getNumOperands()" + EndAdjust + "; i != e; ++i) {");
1179
1180 emitCode(" Ops" + utostr(OpsNo) + ".push_back(N->getOperand(i));");
1181 emitCode("}");
1182 }
1183
1184 // Populate MemRefs with entries for each memory accesses covered by
1185 // this pattern.
1186 if (isRoot && !LSI.empty()) {
1187 std::string MemRefs = "MemRefs" + utostr(OpsNo);
1188 emitCode("MachineSDNode::mmo_iterator " + MemRefs + " = "
1189 "MF->allocateMemRefsArray(" + utostr(LSI.size()) + ");");
1190 for (unsigned i = 0, e = LSI.size(); i != e; ++i)
1191 emitCode(MemRefs + "[" + utostr(i) + "] = "
1192 "cast<MemSDNode>(" + LSI[i] + ")->getMemOperand();");
1193 After.push_back("cast<MachineSDNode>(ResNode)->setMemRefs(" +
1194 MemRefs + ", " + MemRefs + " + " + utostr(LSI.size()) +
1195 ");");
1196 }
1197
1198 if (NodeHasChain) {
1199 if (IsVariadic)
1200 emitCode("Ops" + utostr(OpsNo) + ".push_back(" + ChainName + ");");
1201 else
1202 AllOps.push_back(ChainName);
1203 }
1204
1205 if (IsVariadic) {
1206 if (NodeHasInFlag || HasImpInputs)
1207 emitCode("Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1208 else if (NodeHasOptInFlag) {
1209 emitCode("if (HasInFlag)");
1210 emitCode(" Ops" + utostr(OpsNo) + ".push_back(InFlag);");
1211 }
1212 Code += ", &Ops" + utostr(OpsNo) + "[0], Ops" + utostr(OpsNo) +
1213 ".size()";
1214 } else if (NodeHasInFlag || NodeHasOptInFlag || HasImpInputs)
1215 AllOps.push_back("InFlag");
1216
1217 unsigned NumOps = AllOps.size();
1218 if (NumOps) {
1219 if (!NodeHasOptInFlag && NumOps < 4) {
1220 for (unsigned i = 0; i != NumOps; ++i)
1221 Code += ", " + AllOps[i];
1222 } else {
1223 std::string OpsCode = "SDValue Ops" + utostr(OpsNo) + "[] = { ";
1224 for (unsigned i = 0; i != NumOps; ++i) {
1225 OpsCode += AllOps[i];
1226 if (i != NumOps-1)
1227 OpsCode += ", ";
1228 }
1229 emitCode(OpsCode + " };");
1230 Code += ", Ops" + utostr(OpsNo) + ", ";
1231 if (NodeHasOptInFlag) {
1232 Code += "HasInFlag ? ";
1233 Code += utostr(NumOps) + " : " + utostr(NumOps-1);
1234 } else
1235 Code += utostr(NumOps);
1236 }
1237 }
1238
1239 if (!isRoot)
1240 Code += "), 0";
1241
1242 std::vector<std::string> ReplaceFroms;
1243 std::vector<std::string> ReplaceTos;
1244 if (!isRoot) {
1245 NodeOps.push_back("Tmp" + utostr(ResNo));
1246 } else {
1247
1248 if (NodeHasOutFlag) {
1249 if (!InFlagDecled) {
1250 After.push_back("SDValue InFlag(ResNode, " +
1251 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1252 ");");
1253 InFlagDecled = true;
1254 } else
1255 After.push_back("InFlag = SDValue(ResNode, " +
1256 utostr(NumResults+NumDstRegs+(unsigned)NodeHasChain) +
1257 ");");
1258 }
1259
1260 for (unsigned j = 0, e = FoldedChains.size(); j < e; j++) {
1261 ReplaceFroms.push_back("SDValue(" +
1262 FoldedChains[j].first + ".getNode(), " +
1263 utostr(FoldedChains[j].second) +
1264 ")");
1265 ReplaceTos.push_back("SDValue(ResNode, " +
1266 utostr(NumResults+NumDstRegs) + ")");
1267 }
1268
1269 if (NodeHasOutFlag) {
1270 if (FoldedFlag.first != "") {
1271 ReplaceFroms.push_back("SDValue(" + FoldedFlag.first + ".getNode(), " +
1272 utostr(FoldedFlag.second) + ")");
1273 ReplaceTos.push_back("InFlag");
1274 } else {
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001275 assert(Pattern->NodeHasProperty(SDNPOutFlag, CGP));
Chris Lattner34c50c22010-02-13 20:06:50 +00001276 ReplaceFroms.push_back("SDValue(N, " +
1277 utostr(NumPatResults + (unsigned)InputHasChain)
1278 + ")");
1279 ReplaceTos.push_back("InFlag");
1280 }
1281 }
1282
1283 if (!ReplaceFroms.empty() && InputHasChain) {
1284 ReplaceFroms.push_back("SDValue(N, " +
1285 utostr(NumPatResults) + ")");
1286 ReplaceTos.push_back("SDValue(" + ChainName + ".getNode(), " +
1287 ChainName + ".getResNo()" + ")");
1288 ChainAssignmentNeeded |= NodeHasChain;
1289 }
1290
1291 // User does not expect the instruction would produce a chain!
1292 if ((!InputHasChain && NodeHasChain) && NodeHasOutFlag) {
1293 ;
1294 } else if (InputHasChain && !NodeHasChain) {
1295 // One of the inner node produces a chain.
1296 assert(!NodeHasOutFlag && "Node has flag but not chain!");
1297 ReplaceFroms.push_back("SDValue(N, " +
1298 utostr(NumPatResults) + ")");
1299 ReplaceTos.push_back(ChainName);
1300 }
1301 }
1302
1303 if (ChainAssignmentNeeded) {
1304 // Remember which op produces the chain.
1305 std::string ChainAssign;
1306 if (!isRoot)
1307 ChainAssign = ChainName + " = SDValue(" + NodeName +
1308 ".getNode(), " + utostr(NumResults+NumDstRegs) + ");";
1309 else
1310 ChainAssign = ChainName + " = SDValue(" + NodeName +
1311 ", " + utostr(NumResults+NumDstRegs) + ");";
1312
1313 After.push_front(ChainAssign);
1314 }
1315
1316 if (ReplaceFroms.size() == 1) {
1317 After.push_back("ReplaceUses(" + ReplaceFroms[0] + ", " +
1318 ReplaceTos[0] + ");");
1319 } else if (!ReplaceFroms.empty()) {
1320 After.push_back("const SDValue Froms[] = {");
1321 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1322 After.push_back(" " + ReplaceFroms[i] + (i + 1 != e ? "," : ""));
1323 After.push_back("};");
1324 After.push_back("const SDValue Tos[] = {");
1325 for (unsigned i = 0, e = ReplaceFroms.size(); i != e; ++i)
1326 After.push_back(" " + ReplaceTos[i] + (i + 1 != e ? "," : ""));
1327 After.push_back("};");
1328 After.push_back("ReplaceUses(Froms, Tos, " +
1329 itostr(ReplaceFroms.size()) + ");");
1330 }
1331
1332 // We prefer to use SelectNodeTo since it avoids allocation when
1333 // possible and it avoids CSE map recalculation for the node's
1334 // users, however it's tricky to use in a non-root context.
1335 //
1336 // We also don't use SelectNodeTo if the pattern replacement is being
1337 // used to jettison a chain result, since morphing the node in place
1338 // would leave users of the chain dangling.
1339 //
1340 if (!isRoot || (InputHasChain && !NodeHasChain)) {
1341 Code = "CurDAG->getMachineNode(" + Code;
1342 } else {
1343 Code = "CurDAG->SelectNodeTo(N, " + Code;
1344 }
1345 if (isRoot) {
1346 if (After.empty())
1347 CodePrefix = "return ";
1348 else
1349 After.push_back("return ResNode;");
1350 }
1351
1352 emitCode(CodePrefix + Code + ");");
1353
1354 if (GenDebug) {
1355 if (!isRoot) {
1356 emitCode("CurDAG->setSubgraphColor(" +
1357 NodeName +".getNode(), \"yellow\");");
1358 emitCode("CurDAG->setSubgraphColor(" +
1359 NodeName +".getNode(), \"black\");");
1360 } else {
1361 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"yellow\");");
1362 emitCode("CurDAG->setSubgraphColor(" + NodeName +", \"black\");");
1363 }
1364 }
1365
1366 for (unsigned i = 0, e = After.size(); i != e; ++i)
1367 emitCode(After[i]);
1368
1369 return NodeOps;
1370 }
1371 if (Op->isSubClassOf("SDNodeXForm")) {
1372 assert(N->getNumChildren() == 1 && "node xform should have one child!");
1373 // PatLeaf node - the operand may or may not be a leaf node. But it should
1374 // behave like one.
1375 std::vector<std::string> Ops =
1376 EmitResultCode(N->getChild(0), DstRegs, InFlagDecled,
1377 ResNodeDecled, true);
1378 unsigned ResNo = TmpNo++;
1379 emitCode("SDValue Tmp" + utostr(ResNo) + " = Transform_" + Op->getName()
1380 + "(" + Ops.back() + ".getNode());");
1381 NodeOps.push_back("Tmp" + utostr(ResNo));
1382 if (isRoot)
1383 emitCode("return Tmp" + utostr(ResNo) + ".getNode();");
1384 return NodeOps;
1385 }
1386
1387 N->dump();
1388 errs() << "\n";
1389 throw std::string("Unknown node in result pattern!");
1390}
1391
1392
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393/// EmitCodeForPattern - Given a pattern to match, emit code to the specified
1394/// stream to match the pattern, and generate the code for the match if it
1395/// succeeds. Returns true if the pattern is not guaranteed to match.
Chris Lattner81915752008-01-05 22:30:17 +00001396void DAGISelEmitter::GenerateCodeForPattern(const PatternToMatch &Pattern,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
1398 std::set<std::string> &GeneratedDecl,
1399 std::vector<std::string> &TargetOpcodes,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001400 std::vector<std::string> &TargetVTs,
1401 bool &OutputIsVariadic,
1402 unsigned &NumInputRootOps) {
1403 OutputIsVariadic = false;
1404 NumInputRootOps = 0;
1405
Dan Gohmane97f1a32008-08-22 00:20:26 +00001406 PatternCodeEmitter Emitter(CGP, Pattern.getPredicateCheck(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001407 Pattern.getSrcPattern(), Pattern.getDstPattern(),
1408 GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001409 TargetOpcodes, TargetVTs,
1410 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001411
1412 // Emit the matcher, capturing named arguments in VariableMap.
1413 bool FoundChain = false;
1414 Emitter.EmitMatchCode(Pattern.getSrcPattern(), NULL, "N", "", FoundChain);
1415
Chris Lattner701988b2010-02-14 21:11:53 +00001416 // TP - Get *SOME* tree pattern, we don't care which. It is only used for
1417 // diagnostics, which we know are impossible at this point.
Chris Lattner14948ea2008-01-05 22:58:54 +00001418 TreePattern &TP = *CGP.pf_begin()->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001419
1420 // At this point, we know that we structurally match the pattern, but the
1421 // types of the nodes may not match. Figure out the fewest number of type
1422 // comparisons we need to emit. For example, if there is only one integer
1423 // type supported by a target, there should be no type comparisons at all for
1424 // integer patterns!
1425 //
1426 // To figure out the fewest number of type checks needed, clone the pattern,
1427 // remove the types, then perform type inference on the pattern as a whole.
1428 // If there are unresolved types, emit an explicit check for those types,
1429 // apply the type to the tree, then rerun type inference. Iterate until all
1430 // types are resolved.
1431 //
1432 TreePatternNode *Pat = Pattern.getSrcPattern()->clone();
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001433 Pat->RemoveAllTypes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001434
1435 do {
1436 // Resolve/propagate as many types as possible.
1437 try {
1438 bool MadeChange = true;
1439 while (MadeChange)
1440 MadeChange = Pat->ApplyTypeConstraints(TP,
1441 true/*Ignore reg constraints*/);
1442 } catch (...) {
1443 assert(0 && "Error: could not find consistent types for something we"
1444 " already decided was ok!");
1445 abort();
1446 }
1447
1448 // Insert a check for an unresolved type and add it to the tree. If we find
1449 // an unresolved type to add a check for, this returns true and we iterate,
1450 // otherwise we are done.
1451 } while (Emitter.InsertOneTypeCheck(Pat, Pattern.getSrcPattern(), "N", true));
1452
Evan Cheng775baac2007-09-12 23:30:14 +00001453 Emitter.EmitResultCode(Pattern.getDstPattern(), Pattern.getDstRegs(),
Evan Chengdb1f2462007-09-17 22:26:41 +00001454 false, false, false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001455 delete Pat;
1456}
1457
1458/// EraseCodeLine - Erase one code line from all of the patterns. If removing
1459/// a line causes any of them to be empty, remove them and return true when
1460/// done.
Chris Lattner81915752008-01-05 22:30:17 +00001461static bool EraseCodeLine(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462 std::vector<std::pair<unsigned, std::string> > > >
1463 &Patterns) {
1464 bool ErasedPatterns = false;
1465 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1466 Patterns[i].second.pop_back();
1467 if (Patterns[i].second.empty()) {
1468 Patterns.erase(Patterns.begin()+i);
1469 --i; --e;
1470 ErasedPatterns = true;
1471 }
1472 }
1473 return ErasedPatterns;
1474}
1475
1476/// EmitPatterns - Emit code for at least one pattern, but try to group common
1477/// code together between the patterns.
Chris Lattner81915752008-01-05 22:30:17 +00001478void DAGISelEmitter::EmitPatterns(std::vector<std::pair<const PatternToMatch*,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001479 std::vector<std::pair<unsigned, std::string> > > >
1480 &Patterns, unsigned Indent,
Daniel Dunbard4287062009-07-03 00:10:29 +00001481 raw_ostream &OS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482 typedef std::pair<unsigned, std::string> CodeLine;
1483 typedef std::vector<CodeLine> CodeList;
Chris Lattner81915752008-01-05 22:30:17 +00001484 typedef std::vector<std::pair<const PatternToMatch*, CodeList> > PatternList;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485
1486 if (Patterns.empty()) return;
1487
1488 // Figure out how many patterns share the next code line. Explicitly copy
1489 // FirstCodeLine so that we don't invalidate a reference when changing
1490 // Patterns.
1491 const CodeLine FirstCodeLine = Patterns.back().second.back();
1492 unsigned LastMatch = Patterns.size()-1;
1493 while (LastMatch != 0 && Patterns[LastMatch-1].second.back() == FirstCodeLine)
1494 --LastMatch;
1495
1496 // If not all patterns share this line, split the list into two pieces. The
1497 // first chunk will use this line, the second chunk won't.
1498 if (LastMatch != 0) {
1499 PatternList Shared(Patterns.begin()+LastMatch, Patterns.end());
1500 PatternList Other(Patterns.begin(), Patterns.begin()+LastMatch);
1501
1502 // FIXME: Emit braces?
1503 if (Shared.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001504 const PatternToMatch &Pattern = *Shared.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001505 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1506 Pattern.getSrcPattern()->print(OS);
1507 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1508 Pattern.getDstPattern()->print(OS);
1509 OS << "\n";
1510 unsigned AddedComplexity = Pattern.getAddedComplexity();
1511 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001512 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001513 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001514 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001516 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001517 }
1518 if (FirstCodeLine.first != 1) {
1519 OS << std::string(Indent, ' ') << "{\n";
1520 Indent += 2;
1521 }
1522 EmitPatterns(Shared, Indent, OS);
1523 if (FirstCodeLine.first != 1) {
1524 Indent -= 2;
1525 OS << std::string(Indent, ' ') << "}\n";
1526 }
1527
1528 if (Other.size() == 1) {
Chris Lattner81915752008-01-05 22:30:17 +00001529 const PatternToMatch &Pattern = *Other.back().first;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 OS << "\n" << std::string(Indent, ' ') << "// Pattern: ";
1531 Pattern.getSrcPattern()->print(OS);
1532 OS << "\n" << std::string(Indent, ' ') << "// Emits: ";
1533 Pattern.getDstPattern()->print(OS);
1534 OS << "\n";
1535 unsigned AddedComplexity = Pattern.getAddedComplexity();
1536 OS << std::string(Indent, ' ') << "// Pattern complexity = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001537 << getPatternSize(Pattern.getSrcPattern(), CGP) + AddedComplexity
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001538 << " cost = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001539 << getResultPatternCost(Pattern.getDstPattern(), CGP)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001540 << " size = "
Chris Lattner14948ea2008-01-05 22:58:54 +00001541 << getResultPatternSize(Pattern.getDstPattern(), CGP) << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001542 }
1543 EmitPatterns(Other, Indent, OS);
1544 return;
1545 }
1546
1547 // Remove this code from all of the patterns that share it.
1548 bool ErasedPatterns = EraseCodeLine(Patterns);
1549
1550 bool isPredicate = FirstCodeLine.first == 1;
1551
1552 // Otherwise, every pattern in the list has this line. Emit it.
1553 if (!isPredicate) {
1554 // Normal code.
1555 OS << std::string(Indent, ' ') << FirstCodeLine.second << "\n";
1556 } else {
1557 OS << std::string(Indent, ' ') << "if (" << FirstCodeLine.second;
1558
1559 // If the next code line is another predicate, and if all of the pattern
1560 // in this group share the same next line, emit it inline now. Do this
1561 // until we run out of common predicates.
1562 while (!ErasedPatterns && Patterns.back().second.back().first == 1) {
Jim Grosbachda95ec82009-03-26 16:17:51 +00001563 // Check that all of the patterns in Patterns end with the same predicate.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001564 bool AllEndWithSamePredicate = true;
1565 for (unsigned i = 0, e = Patterns.size(); i != e; ++i)
1566 if (Patterns[i].second.back() != Patterns.back().second.back()) {
1567 AllEndWithSamePredicate = false;
1568 break;
1569 }
1570 // If all of the predicates aren't the same, we can't share them.
1571 if (!AllEndWithSamePredicate) break;
1572
1573 // Otherwise we can. Emit it shared now.
1574 OS << " &&\n" << std::string(Indent+4, ' ')
1575 << Patterns.back().second.back().second;
1576 ErasedPatterns = EraseCodeLine(Patterns);
1577 }
1578
1579 OS << ") {\n";
1580 Indent += 2;
1581 }
1582
1583 EmitPatterns(Patterns, Indent, OS);
1584
1585 if (isPredicate)
1586 OS << std::string(Indent-2, ' ') << "}\n";
1587}
1588
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001589static std::string getLegalCName(std::string OpName) {
1590 std::string::size_type pos = OpName.find("::");
1591 if (pos != std::string::npos)
1592 OpName.replace(pos, 2, "_");
1593 return OpName;
1594}
1595
Daniel Dunbard4287062009-07-03 00:10:29 +00001596void DAGISelEmitter::EmitInstructionSelector(raw_ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001597 const CodeGenTarget &Target = CGP.getTargetInfo();
Chris Lattnere7d6e3c2010-02-15 08:04:42 +00001598
Dan Gohman6a36cc92008-08-20 21:45:57 +00001599 // Get the namespace to insert instructions into.
1600 std::string InstNS = Target.getInstNamespace();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001601 if (!InstNS.empty()) InstNS += "::";
1602
1603 // Group the patterns by their top-level opcodes.
Chris Lattner81915752008-01-05 22:30:17 +00001604 std::map<std::string, std::vector<const PatternToMatch*> > PatternsByOpcode;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605 // All unique target node emission functions.
1606 std::map<std::string, unsigned> EmitFunctions;
Chris Lattnerae506702008-01-06 01:10:31 +00001607 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
Chris Lattner14948ea2008-01-05 22:58:54 +00001608 E = CGP.ptm_end(); I != E; ++I) {
Chris Lattner81915752008-01-05 22:30:17 +00001609 const PatternToMatch &Pattern = *I;
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001610 TreePatternNode *Node = Pattern.getSrcPattern();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001611 if (!Node->isLeaf()) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001612 PatternsByOpcode[getOpcodeName(Node->getOperator(), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001613 push_back(&Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614 } else {
1615 const ComplexPattern *CP;
1616 if (dynamic_cast<IntInit*>(Node->getLeafValue())) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001617 PatternsByOpcode[getOpcodeName(CGP.getSDNodeNamed("imm"), CGP)].
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001618 push_back(&Pattern);
Chris Lattner5c1eb0c2010-02-14 22:22:58 +00001619 } else if ((CP = Node->getComplexPatternInfo(CGP))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001620 std::vector<Record*> OpNodes = CP->getRootNodes();
1621 for (unsigned j = 0, e = OpNodes.size(); j != e; j++) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001622 PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)]
1623 .insert(PatternsByOpcode[getOpcodeName(OpNodes[j], CGP)].begin(),
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001624 &Pattern);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625 }
1626 } else {
Daniel Dunbard4287062009-07-03 00:10:29 +00001627 errs() << "Unrecognized opcode '";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628 Node->dump();
Daniel Dunbard4287062009-07-03 00:10:29 +00001629 errs() << "' on tree pattern '";
1630 errs() << Pattern.getDstPattern()->getOperator()->getName() << "'!\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001631 exit(1);
1632 }
1633 }
1634 }
1635
1636 // For each opcode, there might be multiple select functions, one per
1637 // ValueType of the node (or its first operand if it doesn't produce a
1638 // non-chain result.
1639 std::map<std::string, std::vector<std::string> > OpcodeVTMap;
1640
1641 // Emit one Select_* method for each top-level opcode. We do this instead of
1642 // emitting one giant switch statement to support compilers where this will
1643 // result in the recursive functions taking less stack space.
Chris Lattner81915752008-01-05 22:30:17 +00001644 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1646 PBOI != E; ++PBOI) {
1647 const std::string &OpName = PBOI->first;
Chris Lattner81915752008-01-05 22:30:17 +00001648 std::vector<const PatternToMatch*> &PatternsOfOp = PBOI->second;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001649 assert(!PatternsOfOp.empty() && "No patterns but map has entry?");
1650
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001651 // Split them into groups by type.
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001652 std::map<MVT::SimpleValueType,
Duncan Sands92c43912008-06-06 12:08:01 +00001653 std::vector<const PatternToMatch*> > PatternsByType;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 for (unsigned i = 0, e = PatternsOfOp.size(); i != e; ++i) {
Chris Lattner81915752008-01-05 22:30:17 +00001655 const PatternToMatch *Pat = PatternsOfOp[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001656 TreePatternNode *SrcPat = Pat->getSrcPattern();
Chris Lattner4a5394e2008-08-26 07:01:28 +00001657 PatternsByType[SrcPat->getTypeNum(0)].push_back(Pat);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 }
1659
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001660 for (std::map<MVT::SimpleValueType,
Duncan Sands92c43912008-06-06 12:08:01 +00001661 std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001662 II = PatternsByType.begin(), EE = PatternsByType.end(); II != EE;
1663 ++II) {
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001664 MVT::SimpleValueType OpVT = II->first;
Chris Lattner81915752008-01-05 22:30:17 +00001665 std::vector<const PatternToMatch*> &Patterns = II->second;
Dan Gohman5394e112008-10-15 06:17:21 +00001666 typedef std::pair<unsigned, std::string> CodeLine;
1667 typedef std::vector<CodeLine> CodeList;
1668 typedef CodeList::iterator CodeListI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001669
Chris Lattner81915752008-01-05 22:30:17 +00001670 std::vector<std::pair<const PatternToMatch*, CodeList> > CodeForPatterns;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 std::vector<std::vector<std::string> > PatternOpcodes;
1672 std::vector<std::vector<std::string> > PatternVTs;
1673 std::vector<std::set<std::string> > PatternDecls;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001674 std::vector<bool> OutputIsVariadicFlags;
1675 std::vector<unsigned> NumInputRootOpsCounts;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
1677 CodeList GeneratedCode;
1678 std::set<std::string> GeneratedDecl;
1679 std::vector<std::string> TargetOpcodes;
1680 std::vector<std::string> TargetVTs;
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001681 bool OutputIsVariadic;
1682 unsigned NumInputRootOps;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683 GenerateCodeForPattern(*Patterns[i], GeneratedCode, GeneratedDecl,
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001684 TargetOpcodes, TargetVTs,
1685 OutputIsVariadic, NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001686 CodeForPatterns.push_back(std::make_pair(Patterns[i], GeneratedCode));
1687 PatternDecls.push_back(GeneratedDecl);
1688 PatternOpcodes.push_back(TargetOpcodes);
1689 PatternVTs.push_back(TargetVTs);
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001690 OutputIsVariadicFlags.push_back(OutputIsVariadic);
1691 NumInputRootOpsCounts.push_back(NumInputRootOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001692 }
1693
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001694 // Factor target node emission code (emitted by EmitResultCode) into
1695 // separate functions. Uniquing and share them among all instruction
1696 // selection routines.
1697 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1698 CodeList &GeneratedCode = CodeForPatterns[i].second;
1699 std::vector<std::string> &TargetOpcodes = PatternOpcodes[i];
1700 std::vector<std::string> &TargetVTs = PatternVTs[i];
1701 std::set<std::string> Decls = PatternDecls[i];
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001702 bool OutputIsVariadic = OutputIsVariadicFlags[i];
1703 unsigned NumInputRootOps = NumInputRootOpsCounts[i];
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704 std::vector<std::string> AddedInits;
1705 int CodeSize = (int)GeneratedCode.size();
1706 int LastPred = -1;
1707 for (int j = CodeSize-1; j >= 0; --j) {
1708 if (LastPred == -1 && GeneratedCode[j].first == 1)
1709 LastPred = j;
1710 else if (LastPred != -1 && GeneratedCode[j].first == 2)
1711 AddedInits.push_back(GeneratedCode[j].second);
1712 }
1713
Dan Gohman5f082a72010-01-05 01:24:18 +00001714 std::string CalleeCode = "(SDNode *N";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001715 std::string CallerCode = "(N";
1716 for (unsigned j = 0, e = TargetOpcodes.size(); j != e; ++j) {
1717 CalleeCode += ", unsigned Opc" + utostr(j);
1718 CallerCode += ", " + TargetOpcodes[j];
1719 }
1720 for (unsigned j = 0, e = TargetVTs.size(); j != e; ++j) {
Owen Andersonf2070742009-09-11 09:01:57 +00001721 CalleeCode += ", MVT::SimpleValueType VT" + utostr(j);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 CallerCode += ", " + TargetVTs[j];
1723 }
1724 for (std::set<std::string>::iterator
1725 I = Decls.begin(), E = Decls.end(); I != E; ++I) {
1726 std::string Name = *I;
Dan Gohman8181bd12008-07-27 21:46:04 +00001727 CalleeCode += ", SDValue &" + Name;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001728 CallerCode += ", " + Name;
1729 }
Dan Gohman2c4be2a2008-05-31 02:11:25 +00001730
1731 if (OutputIsVariadic) {
1732 CalleeCode += ", unsigned NumInputRootOps";
1733 CallerCode += ", " + utostr(NumInputRootOps);
1734 }
1735
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001736 CallerCode += ");";
Benjamin Kramer0f5690b2009-11-14 16:37:18 +00001737 CalleeCode += ") {\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738
1739 for (std::vector<std::string>::const_reverse_iterator
1740 I = AddedInits.rbegin(), E = AddedInits.rend(); I != E; ++I)
1741 CalleeCode += " " + *I + "\n";
1742
1743 for (int j = LastPred+1; j < CodeSize; ++j)
1744 CalleeCode += " " + GeneratedCode[j].second + "\n";
1745 for (int j = LastPred+1; j < CodeSize; ++j)
1746 GeneratedCode.pop_back();
1747 CalleeCode += "}\n";
1748
1749 // Uniquing the emission routines.
1750 unsigned EmitFuncNum;
1751 std::map<std::string, unsigned>::iterator EFI =
1752 EmitFunctions.find(CalleeCode);
1753 if (EFI != EmitFunctions.end()) {
1754 EmitFuncNum = EFI->second;
1755 } else {
1756 EmitFuncNum = EmitFunctions.size();
1757 EmitFunctions.insert(std::make_pair(CalleeCode, EmitFuncNum));
Benjamin Kramer0f5690b2009-11-14 16:37:18 +00001758 // Prevent emission routines from being inlined to reduce selection
1759 // routines stack frame sizes.
1760 OS << "DISABLE_INLINE ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761 OS << "SDNode *Emit_" << utostr(EmitFuncNum) << CalleeCode;
1762 }
1763
1764 // Replace the emission code within selection routines with calls to the
1765 // emission functions.
Chris Lattner34c50c22010-02-13 20:06:50 +00001766 if (GenDebug)
Dan Gohman5f082a72010-01-05 01:24:18 +00001767 GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"red\");"));
David Greene932618b2008-10-27 21:56:29 +00001768 CallerCode = "SDNode *Result = Emit_" + utostr(EmitFuncNum) + CallerCode;
1769 GeneratedCode.push_back(std::make_pair(3, CallerCode));
1770 if (GenDebug) {
1771 GeneratedCode.push_back(std::make_pair(0, "if(Result) {"));
1772 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"yellow\");"));
1773 GeneratedCode.push_back(std::make_pair(0, " CurDAG->setSubgraphColor(Result, \"black\");"));
1774 GeneratedCode.push_back(std::make_pair(0, "}"));
Dan Gohman5f082a72010-01-05 01:24:18 +00001775 //GeneratedCode.push_back(std::make_pair(0, "CurDAG->setSubgraphColor(N, \"black\");"));
David Greene932618b2008-10-27 21:56:29 +00001776 }
1777 GeneratedCode.push_back(std::make_pair(0, "return Result;"));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001778 }
1779
1780 // Print function.
1781 std::string OpVTStr;
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001782 if (OpVT == MVT::iPTR) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783 OpVTStr = "_iPTR";
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001784 } else if (OpVT == MVT::iPTRAny) {
Mon P Wangce3ac892008-07-30 04:36:53 +00001785 OpVTStr = "_iPTRAny";
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001786 } else if (OpVT == MVT::isVoid) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001787 // Nodes with a void result actually have a first result type of either
1788 // Other (a chain) or Flag. Since there is no one-to-one mapping from
1789 // void to this case, we handle it specially here.
1790 } else {
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001791 OpVTStr = "_" + getEnumName(OpVT).substr(5); // Skip 'MVT::'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001792 }
1793 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1794 OpcodeVTMap.find(OpName);
1795 if (OpVTI == OpcodeVTMap.end()) {
1796 std::vector<std::string> VTSet;
1797 VTSet.push_back(OpVTStr);
1798 OpcodeVTMap.insert(std::make_pair(OpName, VTSet));
1799 } else
1800 OpVTI->second.push_back(OpVTStr);
1801
Dan Gohman5394e112008-10-15 06:17:21 +00001802 // We want to emit all of the matching code now. However, we want to emit
1803 // the matches in order of minimal cost. Sort the patterns so the least
1804 // cost one is at the start.
1805 std::stable_sort(CodeForPatterns.begin(), CodeForPatterns.end(),
1806 PatternSortingPredicate(CGP));
1807
1808 // Scan the code to see if all of the patterns are reachable and if it is
1809 // possible that the last one might not match.
1810 bool mightNotMatch = true;
1811 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1812 CodeList &GeneratedCode = CodeForPatterns[i].second;
1813 mightNotMatch = false;
1814
1815 for (unsigned j = 0, e = GeneratedCode.size(); j != e; ++j) {
1816 if (GeneratedCode[j].first == 1) { // predicate.
1817 mightNotMatch = true;
1818 break;
1819 }
1820 }
1821
1822 // If this pattern definitely matches, and if it isn't the last one, the
1823 // patterns after it CANNOT ever match. Error out.
1824 if (mightNotMatch == false && i != CodeForPatterns.size()-1) {
Daniel Dunbard4287062009-07-03 00:10:29 +00001825 errs() << "Pattern '";
1826 CodeForPatterns[i].first->getSrcPattern()->print(errs());
1827 errs() << "' is impossible to select!\n";
Dan Gohman5394e112008-10-15 06:17:21 +00001828 exit(1);
1829 }
1830 }
1831
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001832 // Loop through and reverse all of the CodeList vectors, as we will be
1833 // accessing them from their logical front, but accessing the end of a
1834 // vector is more efficient.
1835 for (unsigned i = 0, e = CodeForPatterns.size(); i != e; ++i) {
1836 CodeList &GeneratedCode = CodeForPatterns[i].second;
1837 std::reverse(GeneratedCode.begin(), GeneratedCode.end());
1838 }
1839
1840 // Next, reverse the list of patterns itself for the same reason.
1841 std::reverse(CodeForPatterns.begin(), CodeForPatterns.end());
1842
Dan Gohman4b975a92009-01-29 01:37:18 +00001843 OS << "SDNode *Select_" << getLegalCName(OpName)
Dan Gohman5f082a72010-01-05 01:24:18 +00001844 << OpVTStr << "(SDNode *N) {\n";
Dan Gohman4b975a92009-01-29 01:37:18 +00001845
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001846 // Emit all of the patterns now, grouped together to share code.
1847 EmitPatterns(CodeForPatterns, 2, OS);
1848
1849 // If the last pattern has predicates (which could fail) emit code to
1850 // catch the case where nothing handles a pattern.
1851 if (mightNotMatch) {
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001852 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853 if (OpName != "ISD::INTRINSIC_W_CHAIN" &&
1854 OpName != "ISD::INTRINSIC_WO_CHAIN" &&
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001855 OpName != "ISD::INTRINSIC_VOID")
1856 OS << " CannotYetSelect(N);\n";
1857 else
1858 OS << " CannotYetSelectIntrinsic(N);\n";
1859
1860 OS << " return NULL;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001861 }
1862 OS << "}\n\n";
1863 }
1864 }
1865
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001866 OS << "// The main instruction selector code.\n"
Dan Gohman5f082a72010-01-05 01:24:18 +00001867 << "SDNode *SelectCode(SDNode *N) {\n"
1868 << " MVT::SimpleValueType NVT = N->getValueType(0).getSimpleVT().SimpleTy;\n"
1869 << " switch (N->getOpcode()) {\n"
Dan Gohman231412c2008-11-05 18:30:52 +00001870 << " default:\n"
Dan Gohman5f082a72010-01-05 01:24:18 +00001871 << " assert(!N->isMachineOpcode() && \"Node already selected!\");\n"
Dan Gohman231412c2008-11-05 18:30:52 +00001872 << " break;\n"
1873 << " case ISD::EntryToken: // These nodes remain the same.\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874 << " case ISD::BasicBlock:\n"
1875 << " case ISD::Register:\n"
1876 << " case ISD::HANDLENODE:\n"
1877 << " case ISD::TargetConstant:\n"
Nate Begemane2ba64f2008-02-14 08:57:00 +00001878 << " case ISD::TargetConstantFP:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001879 << " case ISD::TargetConstantPool:\n"
1880 << " case ISD::TargetFrameIndex:\n"
Bill Wendlingfef06052008-09-16 21:48:12 +00001881 << " case ISD::TargetExternalSymbol:\n"
Dan Gohman91057512009-10-30 01:27:03 +00001882 << " case ISD::TargetBlockAddress:\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001883 << " case ISD::TargetJumpTable:\n"
1884 << " case ISD::TargetGlobalTLSAddress:\n"
Dan Gohmancc3df852008-11-05 04:14:16 +00001885 << " case ISD::TargetGlobalAddress:\n"
1886 << " case ISD::TokenFactor:\n"
1887 << " case ISD::CopyFromReg:\n"
1888 << " case ISD::CopyToReg: {\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001889 << " return NULL;\n"
1890 << " }\n"
1891 << " case ISD::AssertSext:\n"
1892 << " case ISD::AssertZext: {\n"
Dan Gohman5f082a72010-01-05 01:24:18 +00001893 << " ReplaceUses(SDValue(N, 0), N->getOperand(0));\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894 << " return NULL;\n"
1895 << " }\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001896 << " case ISD::INLINEASM: return Select_INLINEASM(N);\n"
Dan Gohman7eced112008-07-02 23:23:19 +00001897 << " case ISD::EH_LABEL: return Select_EH_LABEL(N);\n"
Evan Cheng3c0eda52008-03-15 00:03:38 +00001898 << " case ISD::UNDEF: return Select_UNDEF(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001899
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001900 // Loop over all of the case statements, emiting a call to each method we
1901 // emitted above.
Chris Lattner81915752008-01-05 22:30:17 +00001902 for (std::map<std::string, std::vector<const PatternToMatch*> >::iterator
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 PBOI = PatternsByOpcode.begin(), E = PatternsByOpcode.end();
1904 PBOI != E; ++PBOI) {
1905 const std::string &OpName = PBOI->first;
1906 // Potentially multiple versions of select for this opcode. One for each
1907 // ValueType of the node (or its first true operand if it doesn't produce a
1908 // result.
1909 std::map<std::string, std::vector<std::string> >::iterator OpVTI =
1910 OpcodeVTMap.find(OpName);
1911 std::vector<std::string> &OpVTs = OpVTI->second;
1912 OS << " case " << OpName << ": {\n";
Dale Johannesendf9cd7d2009-05-12 22:32:29 +00001913 // If we have only one variant and it's the default, elide the
1914 // switch. Marginally faster, and makes MSVC happier.
1915 if (OpVTs.size()==1 && OpVTs[0].empty()) {
1916 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1917 OS << " break;\n";
1918 OS << " }\n";
1919 continue;
1920 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001921 // Keep track of whether we see a pattern that has an iPtr result.
1922 bool HasPtrPattern = false;
1923 bool HasDefaultPattern = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001924
Evan Chengb8b6b182007-09-04 20:18:28 +00001925 OS << " switch (NVT) {\n";
1926 for (unsigned i = 0, e = OpVTs.size(); i < e; ++i) {
1927 std::string &VTStr = OpVTs[i];
1928 if (VTStr.empty()) {
1929 HasDefaultPattern = true;
1930 continue;
1931 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001932
Evan Chengb8b6b182007-09-04 20:18:28 +00001933 // If this is a match on iPTR: don't emit it directly, we need special
1934 // code.
1935 if (VTStr == "_iPTR") {
1936 HasPtrPattern = true;
1937 continue;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001938 }
Owen Anderson36e3a6e2009-08-11 20:47:22 +00001939 OS << " case MVT::" << VTStr.substr(1) << ":\n"
Evan Chengb8b6b182007-09-04 20:18:28 +00001940 << " return Select_" << getLegalCName(OpName)
1941 << VTStr << "(N);\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001942 }
Evan Chengb8b6b182007-09-04 20:18:28 +00001943 OS << " default:\n";
1944
1945 // If there is an iPTR result version of this pattern, emit it here.
1946 if (HasPtrPattern) {
Duncan Sands92c43912008-06-06 12:08:01 +00001947 OS << " if (TLI.getPointerTy() == NVT)\n";
Evan Chengb8b6b182007-09-04 20:18:28 +00001948 OS << " return Select_" << getLegalCName(OpName) <<"_iPTR(N);\n";
1949 }
1950 if (HasDefaultPattern) {
1951 OS << " return Select_" << getLegalCName(OpName) << "(N);\n";
1952 }
1953 OS << " break;\n";
1954 OS << " }\n";
1955 OS << " break;\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 OS << " }\n";
1957 }
1958
1959 OS << " } // end of big switch.\n\n"
Dan Gohman5f082a72010-01-05 01:24:18 +00001960 << " if (N->getOpcode() != ISD::INTRINSIC_W_CHAIN &&\n"
1961 << " N->getOpcode() != ISD::INTRINSIC_WO_CHAIN &&\n"
1962 << " N->getOpcode() != ISD::INTRINSIC_VOID) {\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001963 << " CannotYetSelect(N);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001964 << " } else {\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001965 << " CannotYetSelectIntrinsic(N);\n"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966 << " }\n"
Dan Gohmanc7fa4252008-09-27 23:53:14 +00001967 << " return NULL;\n"
1968 << "}\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001969}
1970
Daniel Dunbard4287062009-07-03 00:10:29 +00001971void DAGISelEmitter::run(raw_ostream &OS) {
Chris Lattner14948ea2008-01-05 22:58:54 +00001972 EmitSourceFileHeader("DAG Instruction Selector for the " +
1973 CGP.getTargetInfo().getName() + " target", OS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001974
1975 OS << "// *** NOTE: This file is #included into the middle of the target\n"
1976 << "// *** instruction selector class. These functions are really "
1977 << "methods.\n\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00001978
Roman Levenstein393ad0f2008-05-14 10:17:11 +00001979 OS << "// Include standard, target-independent definitions and methods used\n"
1980 << "// by the instruction selector.\n";
asl7a969d82009-05-04 19:10:38 +00001981 OS << "#include \"llvm/CodeGen/DAGISelHeader.h\"\n\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001982
Chris Lattner227da452008-01-05 22:54:53 +00001983 EmitNodeTransforms(OS);
Chris Lattner7fdd9342008-01-05 22:43:57 +00001984 EmitPredicateFunctions(OS);
1985
Chris Lattner006d7d82009-08-23 04:44:11 +00001986 DEBUG(errs() << "\n\nALL PATTERNS TO MATCH:\n\n");
Chris Lattnerae506702008-01-06 01:10:31 +00001987 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(), E = CGP.ptm_end();
Chris Lattner4ca8ff02008-01-05 22:25:12 +00001988 I != E; ++I) {
Chris Lattner006d7d82009-08-23 04:44:11 +00001989 DEBUG(errs() << "PATTERN: "; I->getSrcPattern()->dump());
1990 DEBUG(errs() << "\nRESULT: "; I->getDstPattern()->dump());
1991 DEBUG(errs() << "\n");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001992 }
1993
1994 // At this point, we have full information about the 'Patterns' we need to
1995 // parse, both implicitly from instructions as well as from explicit pattern
1996 // definitions. Emit the resultant instruction selector.
1997 EmitInstructionSelector(OS);
1998
Chris Lattnere7d6e3c2010-02-15 08:04:42 +00001999#if 0
2000 MatcherNode *Matcher = 0;
2001 // Walk the patterns backwards, building a matcher for each and adding it to
2002 // the matcher for the whole target.
2003 for (CodeGenDAGPatterns::ptm_iterator I = CGP.ptm_begin(),
2004 E = CGP.ptm_end(); I != E;) {
2005 const PatternToMatch &Pattern = *--E;
2006 MatcherNode *N = ConvertPatternToMatcher(Pattern, CGP);
2007
2008 if (Matcher == 0)
2009 Matcher = N;
2010 else
2011 Matcher = new PushMatcherNode(N, Matcher);
2012 }
2013
2014
2015 EmitMatcherTable(Matcher, OS);
2016
2017
2018 //Matcher->dump();
2019 delete Matcher;
2020#endif
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002021}