1 //===- DAGISelEmitter.h - Generate an instruction selector ------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend emits a DAG instruction selector.
12 //===----------------------------------------------------------------------===//
14 #ifndef DAGISEL_EMITTER_H
15 #define DAGISEL_EMITTER_H
17 #include "TableGenBackend.h"
18 #include "CodeGenTarget.h"
28 class TreePatternNode;
32 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
33 /// that we use as lattice values during type inferrence.
35 enum DAGISelGenValueType {
36 isFP = MVT::LAST_VALUETYPE,
42 /// SDTypeConstraint - This is a discriminated union of constraints,
43 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
44 struct SDTypeConstraint {
45 SDTypeConstraint(Record *R);
47 unsigned OperandNo; // The operand # this constraint applies to.
49 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
50 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize
53 union { // The discriminated union.
58 unsigned OtherOperandNum;
61 unsigned OtherOperandNum;
62 } SDTCisVTSmallerThanOp_Info;
64 unsigned BigOperandNum;
65 } SDTCisOpSmallerThanOp_Info;
67 unsigned OtherOperandNum;
68 } SDTCisIntVectorOfSameSize_Info;
71 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
72 /// constraint to the nodes operands. This returns true if it makes a
73 /// change, false otherwise. If a type contradiction is found, throw an
75 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
76 TreePattern &TP) const;
78 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
79 /// N, which has NumResults results.
80 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
81 unsigned NumResults) const;
84 /// SDNodeInfo - One of these records is created for each SDNode instance in
85 /// the target .td file. This represents the various dag nodes we will be
90 std::string SDClassName;
94 std::vector<SDTypeConstraint> TypeConstraints;
96 SDNodeInfo(Record *R); // Parse the specified record.
98 unsigned getNumResults() const { return NumResults; }
99 int getNumOperands() const { return NumOperands; }
100 Record *getRecord() const { return Def; }
101 const std::string &getEnumName() const { return EnumName; }
102 const std::string &getSDClassName() const { return SDClassName; }
104 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
105 return TypeConstraints;
108 // SelectionDAG node properties.
109 enum SDNP { SDNPCommutative, SDNPAssociative, SDNPHasChain,
110 SDNPOutFlag, SDNPInFlag, SDNPOptInFlag };
112 /// hasProperty - Return true if this node has the specified property.
114 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
116 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
117 /// constraints for this node to the operands of the node. This returns
118 /// true if it makes a change, false otherwise. If a type contradiction is
119 /// found, throw an exception.
120 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
121 bool MadeChange = false;
122 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
123 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
128 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
129 /// patterns), and as such should be ref counted. We currently just leak all
130 /// TreePatternNode objects!
131 class TreePatternNode {
132 /// The inferred type for this node, or MVT::isUnknown if it hasn't
133 /// been determined yet.
134 std::vector<unsigned char> Types;
136 /// Operator - The Record for the operator if this is an interior node (not
140 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
144 /// Name - The name given to this node with the :$foo notation.
148 /// PredicateFn - The predicate function to execute on this node to check
149 /// for a match. If this string is empty, no predicate is involved.
150 std::string PredicateFn;
152 /// TransformFn - The transformation function to execute on this node before
153 /// it can be substituted into the resulting instruction on a pattern match.
156 std::vector<TreePatternNode*> Children;
158 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
159 : Types(), Operator(Op), Val(0), TransformFn(0),
160 Children(Ch) { Types.push_back(MVT::isUnknown); }
161 TreePatternNode(Init *val) // leaf ctor
162 : Types(), Operator(0), Val(val), TransformFn(0) {
163 Types.push_back(MVT::isUnknown);
167 const std::string &getName() const { return Name; }
168 void setName(const std::string &N) { Name = N; }
170 bool isLeaf() const { return Val != 0; }
171 bool hasTypeSet() const { return Types[0] < MVT::LAST_VALUETYPE; }
172 bool isTypeCompletelyUnknown() const {
173 return Types[0] == MVT::isUnknown;
175 MVT::ValueType getTypeNum(unsigned Num) const {
176 assert(hasTypeSet() && "Doesn't have a type yet!");
177 assert(Types.size() > Num && "Type num out of range!");
178 return (MVT::ValueType)Types[Num];
180 unsigned char getExtTypeNum(unsigned Num) const {
181 assert(Types.size() > Num && "Extended type num out of range!");
184 const std::vector<unsigned char> &getExtTypes() const { return Types; }
185 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
186 void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
188 Init *getLeafValue() const { assert(isLeaf()); return Val; }
189 Record *getOperator() const { assert(!isLeaf()); return Operator; }
191 unsigned getNumChildren() const { return Children.size(); }
192 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
193 void setChild(unsigned i, TreePatternNode *N) {
198 const std::string &getPredicateFn() const { return PredicateFn; }
199 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
201 Record *getTransformFn() const { return TransformFn; }
202 void setTransformFn(Record *Fn) { TransformFn = Fn; }
204 void print(std::ostream &OS) const;
207 public: // Higher level manipulation routines.
209 /// clone - Return a new copy of this tree.
211 TreePatternNode *clone() const;
213 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
214 /// the specified node. For this comparison, all of the state of the node
215 /// is considered, except for the assigned name. Nodes with differing names
216 /// that are otherwise identical are considered isomorphic.
217 bool isIsomorphicTo(const TreePatternNode *N) const;
219 /// SubstituteFormalArguments - Replace the formal arguments in this tree
220 /// with actual values specified by ArgMap.
221 void SubstituteFormalArguments(std::map<std::string,
222 TreePatternNode*> &ArgMap);
224 /// InlinePatternFragments - If this pattern refers to any pattern
225 /// fragments, inline them into place, giving us a pattern without any
226 /// PatFrag references.
227 TreePatternNode *InlinePatternFragments(TreePattern &TP);
229 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
230 /// this node and its children in the tree. This returns true if it makes a
231 /// change, false otherwise. If a type contradiction is found, throw an
233 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
235 /// UpdateNodeType - Set the node type of N to VT if VT contains
236 /// information. If N already contains a conflicting type, then throw an
237 /// exception. This returns true if any information was updated.
239 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
241 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
242 std::vector<unsigned char> ExtVTs(1, ExtVT);
243 return UpdateNodeType(ExtVTs, TP);
246 /// ContainsUnresolvedType - Return true if this tree contains any
247 /// unresolved types.
248 bool ContainsUnresolvedType() const {
249 if (!hasTypeSet()) return true;
250 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
251 if (getChild(i)->ContainsUnresolvedType()) return true;
255 /// canPatternMatch - If it is impossible for this pattern to match on this
256 /// target, fill in Reason and return false. Otherwise, return true.
257 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
261 /// TreePattern - Represent a pattern, used for instructions, pattern
265 /// Trees - The list of pattern trees which corresponds to this pattern.
266 /// Note that PatFrag's only have a single tree.
268 std::vector<TreePatternNode*> Trees;
270 /// TheRecord - The actual TableGen record corresponding to this pattern.
274 /// Args - This is a list of all of the arguments to this pattern (for
275 /// PatFrag patterns), which are the 'node' markers in this pattern.
276 std::vector<std::string> Args;
278 /// ISE - the DAG isel emitter coordinating this madness.
282 /// isInputPattern - True if this is an input pattern, something to match.
283 /// False if this is an output pattern, something to emit.
287 /// TreePattern constructor - Parse the specified DagInits into the
289 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
290 DAGISelEmitter &ise);
291 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
292 DAGISelEmitter &ise);
293 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
294 DAGISelEmitter &ise);
296 /// getTrees - Return the tree patterns which corresponds to this pattern.
298 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
299 unsigned getNumTrees() const { return Trees.size(); }
300 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
301 TreePatternNode *getOnlyTree() const {
302 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
306 /// getRecord - Return the actual TableGen record corresponding to this
309 Record *getRecord() const { return TheRecord; }
311 unsigned getNumArgs() const { return Args.size(); }
312 const std::string &getArgName(unsigned i) const {
313 assert(i < Args.size() && "Argument reference out of range!");
316 std::vector<std::string> &getArgList() { return Args; }
318 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
320 /// InlinePatternFragments - If this pattern refers to any pattern
321 /// fragments, inline them into place, giving us a pattern without any
322 /// PatFrag references.
323 void InlinePatternFragments() {
324 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
325 Trees[i] = Trees[i]->InlinePatternFragments(*this);
328 /// InferAllTypes - Infer/propagate as many types throughout the expression
329 /// patterns as possible. Return true if all types are infered, false
330 /// otherwise. Throw an exception if a type contradiction is found.
331 bool InferAllTypes();
333 /// error - Throw an exception, prefixing it with information about this
335 void error(const std::string &Msg) const;
337 void print(std::ostream &OS) const;
341 TreePatternNode *ParseTreePattern(DagInit *DI);
345 class DAGInstruction {
346 TreePattern *Pattern;
347 std::vector<Record*> Results;
348 std::vector<Record*> Operands;
349 std::vector<Record*> ImpResults;
350 std::vector<Record*> ImpOperands;
351 TreePatternNode *ResultPattern;
353 DAGInstruction(TreePattern *TP,
354 const std::vector<Record*> &results,
355 const std::vector<Record*> &operands,
356 const std::vector<Record*> &impresults,
357 const std::vector<Record*> &impoperands)
358 : Pattern(TP), Results(results), Operands(operands),
359 ImpResults(impresults), ImpOperands(impoperands),
362 TreePattern *getPattern() const { return Pattern; }
363 unsigned getNumResults() const { return Results.size(); }
364 unsigned getNumOperands() const { return Operands.size(); }
365 unsigned getNumImpResults() const { return ImpResults.size(); }
366 unsigned getNumImpOperands() const { return ImpOperands.size(); }
368 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
370 Record *getResult(unsigned RN) const {
371 assert(RN < Results.size());
375 Record *getOperand(unsigned ON) const {
376 assert(ON < Operands.size());
380 Record *getImpResult(unsigned RN) const {
381 assert(RN < ImpResults.size());
382 return ImpResults[RN];
385 Record *getImpOperand(unsigned ON) const {
386 assert(ON < ImpOperands.size());
387 return ImpOperands[ON];
390 TreePatternNode *getResultPattern() const { return ResultPattern; }
393 /// PatternToMatch - Used by DAGISelEmitter to keep tab of patterns processed
395 struct PatternToMatch {
396 PatternToMatch(ListInit *preds, TreePatternNode *src, TreePatternNode *dst):
397 Predicates(preds), SrcPattern(src), DstPattern(dst) {};
399 ListInit *Predicates; // Top level predicate conditions to match.
400 TreePatternNode *SrcPattern; // Source pattern to match.
401 TreePatternNode *DstPattern; // Resulting pattern.
403 ListInit *getPredicates() const { return Predicates; }
404 TreePatternNode *getSrcPattern() const { return SrcPattern; }
405 TreePatternNode *getDstPattern() const { return DstPattern; }
408 /// DAGISelEmitter - The top-level class which coordinates construction
409 /// and emission of the instruction selector.
411 class DAGISelEmitter : public TableGenBackend {
413 RecordKeeper &Records;
414 CodeGenTarget Target;
416 std::map<Record*, SDNodeInfo> SDNodes;
417 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
418 std::map<Record*, ComplexPattern> ComplexPatterns;
419 std::map<Record*, TreePattern*> PatternFragments;
420 std::map<Record*, DAGInstruction> Instructions;
422 /// PatternsToMatch - All of the things we are matching on the DAG. The first
423 /// value is the pattern to match, the second pattern is the result to
425 std::vector<PatternToMatch> PatternsToMatch;
427 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
429 // run - Output the isel, returning true on failure.
430 void run(std::ostream &OS);
432 const CodeGenTarget &getTargetInfo() const { return Target; }
434 Record *getSDNodeNamed(const std::string &Name) const;
436 const SDNodeInfo &getSDNodeInfo(Record *R) const {
437 assert(SDNodes.count(R) && "Unknown node!");
438 return SDNodes.find(R)->second;
441 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
442 assert(SDNodeXForms.count(R) && "Invalid transform!");
443 return SDNodeXForms.find(R)->second;
446 const ComplexPattern &getComplexPattern(Record *R) const {
447 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
448 return ComplexPatterns.find(R)->second;
451 TreePattern *getPatternFragment(Record *R) const {
452 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
453 return PatternFragments.find(R)->second;
456 const DAGInstruction &getInstruction(Record *R) const {
457 assert(Instructions.count(R) && "Unknown instruction!");
458 return Instructions.find(R)->second;
462 void ParseNodeInfo();
463 void ParseNodeTransforms(std::ostream &OS);
464 void ParseComplexPatterns();
465 void ParsePatternFragments(std::ostream &OS);
466 void ParseInstructions();
467 void ParsePatterns();
468 void GenerateVariants();
469 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
470 std::map<std::string,
471 TreePatternNode*> &InstInputs,
472 std::map<std::string,
473 TreePatternNode*> &InstResults,
474 std::vector<Record*> &InstImpInputs,
475 std::vector<Record*> &InstImpResults);
476 void GenerateCodeForPattern(PatternToMatch &Pattern,
477 std::vector<std::pair<bool, std::string> > &GeneratedCode,
478 std::set<std::pair<bool, std::string> > &GeneratedDecl,
480 void EmitPatterns(std::vector<std::pair<PatternToMatch*,
481 std::vector<std::pair<bool, std::string> > > > &Patterns,
482 unsigned Indent, std::ostream &OS);
483 void EmitInstructionSelector(std::ostream &OS);
486 } // End llvm namespace