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
53 union { // The discriminated union.
58 unsigned OtherOperandNum;
61 unsigned OtherOperandNum;
62 } SDTCisVTSmallerThanOp_Info;
64 unsigned BigOperandNum;
65 } SDTCisOpSmallerThanOp_Info;
68 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
69 /// constraint to the nodes operands. This returns true if it makes a
70 /// change, false otherwise. If a type contradiction is found, throw an
72 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
73 TreePattern &TP) const;
75 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
76 /// N, which has NumResults results.
77 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
78 unsigned NumResults) const;
81 /// SDNodeInfo - One of these records is created for each SDNode instance in
82 /// the target .td file. This represents the various dag nodes we will be
87 std::string SDClassName;
91 std::vector<SDTypeConstraint> TypeConstraints;
93 SDNodeInfo(Record *R); // Parse the specified record.
95 unsigned getNumResults() const { return NumResults; }
96 int getNumOperands() const { return NumOperands; }
97 Record *getRecord() const { return Def; }
98 const std::string &getEnumName() const { return EnumName; }
99 const std::string &getSDClassName() const { return SDClassName; }
101 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
102 return TypeConstraints;
105 // SelectionDAG node properties.
106 enum SDNP { SDNPCommutative, SDNPAssociative, SDNPHasChain,
107 SDNPOutFlag, SDNPInFlag, SDNPOptInFlag };
109 /// hasProperty - Return true if this node has the specified property.
111 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
113 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
114 /// constraints for this node to the operands of the node. This returns
115 /// true if it makes a change, false otherwise. If a type contradiction is
116 /// found, throw an exception.
117 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
118 bool MadeChange = false;
119 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
120 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
125 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
126 /// patterns), and as such should be ref counted. We currently just leak all
127 /// TreePatternNode objects!
128 class TreePatternNode {
129 /// The inferred type for this node, or MVT::isUnknown if it hasn't
130 /// been determined yet.
131 std::vector<unsigned char> Types;
133 /// Operator - The Record for the operator if this is an interior node (not
137 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
141 /// Name - The name given to this node with the :$foo notation.
145 /// PredicateFn - The predicate function to execute on this node to check
146 /// for a match. If this string is empty, no predicate is involved.
147 std::string PredicateFn;
149 /// TransformFn - The transformation function to execute on this node before
150 /// it can be substituted into the resulting instruction on a pattern match.
153 std::vector<TreePatternNode*> Children;
155 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
156 : Types(), Operator(Op), Val(0), TransformFn(0),
157 Children(Ch) { Types.push_back(MVT::isUnknown); }
158 TreePatternNode(Init *val) // leaf ctor
159 : Types(), Operator(0), Val(val), TransformFn(0) {
160 Types.push_back(MVT::isUnknown);
164 const std::string &getName() const { return Name; }
165 void setName(const std::string &N) { Name = N; }
167 bool isLeaf() const { return Val != 0; }
168 bool hasTypeSet() const { return Types[0] < MVT::LAST_VALUETYPE; }
169 bool isTypeCompletelyUnknown() const {
170 return Types[0] == MVT::isUnknown;
172 MVT::ValueType getTypeNum(unsigned Num) const {
173 assert(hasTypeSet() && "Doesn't have a type yet!");
174 assert(Types.size() > Num && "Type num out of range!");
175 return (MVT::ValueType)Types[Num];
177 unsigned char getExtTypeNum(unsigned Num) const {
178 assert(Types.size() > Num && "Extended type num out of range!");
181 const std::vector<unsigned char> &getExtTypes() const { return Types; }
182 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
183 void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
185 Init *getLeafValue() const { assert(isLeaf()); return Val; }
186 Record *getOperator() const { assert(!isLeaf()); return Operator; }
188 unsigned getNumChildren() const { return Children.size(); }
189 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
190 void setChild(unsigned i, TreePatternNode *N) {
195 const std::string &getPredicateFn() const { return PredicateFn; }
196 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
198 Record *getTransformFn() const { return TransformFn; }
199 void setTransformFn(Record *Fn) { TransformFn = Fn; }
201 void print(std::ostream &OS) const;
204 public: // Higher level manipulation routines.
206 /// clone - Return a new copy of this tree.
208 TreePatternNode *clone() const;
210 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
211 /// the specified node. For this comparison, all of the state of the node
212 /// is considered, except for the assigned name. Nodes with differing names
213 /// that are otherwise identical are considered isomorphic.
214 bool isIsomorphicTo(const TreePatternNode *N) const;
216 /// SubstituteFormalArguments - Replace the formal arguments in this tree
217 /// with actual values specified by ArgMap.
218 void SubstituteFormalArguments(std::map<std::string,
219 TreePatternNode*> &ArgMap);
221 /// InlinePatternFragments - If this pattern refers to any pattern
222 /// fragments, inline them into place, giving us a pattern without any
223 /// PatFrag references.
224 TreePatternNode *InlinePatternFragments(TreePattern &TP);
226 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
227 /// this node and its children in the tree. This returns true if it makes a
228 /// change, false otherwise. If a type contradiction is found, throw an
230 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
232 /// UpdateNodeType - Set the node type of N to VT if VT contains
233 /// information. If N already contains a conflicting type, then throw an
234 /// exception. This returns true if any information was updated.
236 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
238 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
239 std::vector<unsigned char> ExtVTs(1, ExtVT);
240 return UpdateNodeType(ExtVTs, TP);
243 /// ContainsUnresolvedType - Return true if this tree contains any
244 /// unresolved types.
245 bool ContainsUnresolvedType() const {
246 if (!hasTypeSet()) return true;
247 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
248 if (getChild(i)->ContainsUnresolvedType()) return true;
252 /// canPatternMatch - If it is impossible for this pattern to match on this
253 /// target, fill in Reason and return false. Otherwise, return true.
254 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
258 /// TreePattern - Represent a pattern, used for instructions, pattern
262 /// Trees - The list of pattern trees which corresponds to this pattern.
263 /// Note that PatFrag's only have a single tree.
265 std::vector<TreePatternNode*> Trees;
267 /// TheRecord - The actual TableGen record corresponding to this pattern.
271 /// Args - This is a list of all of the arguments to this pattern (for
272 /// PatFrag patterns), which are the 'node' markers in this pattern.
273 std::vector<std::string> Args;
275 /// ISE - the DAG isel emitter coordinating this madness.
279 /// isInputPattern - True if this is an input pattern, something to match.
280 /// False if this is an output pattern, something to emit.
284 /// TreePattern constructor - Parse the specified DagInits into the
286 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
287 DAGISelEmitter &ise);
288 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
289 DAGISelEmitter &ise);
290 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
291 DAGISelEmitter &ise);
293 /// getTrees - Return the tree patterns which corresponds to this pattern.
295 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
296 unsigned getNumTrees() const { return Trees.size(); }
297 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
298 TreePatternNode *getOnlyTree() const {
299 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
303 /// getRecord - Return the actual TableGen record corresponding to this
306 Record *getRecord() const { return TheRecord; }
308 unsigned getNumArgs() const { return Args.size(); }
309 const std::string &getArgName(unsigned i) const {
310 assert(i < Args.size() && "Argument reference out of range!");
313 std::vector<std::string> &getArgList() { return Args; }
315 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
317 /// InlinePatternFragments - If this pattern refers to any pattern
318 /// fragments, inline them into place, giving us a pattern without any
319 /// PatFrag references.
320 void InlinePatternFragments() {
321 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
322 Trees[i] = Trees[i]->InlinePatternFragments(*this);
325 /// InferAllTypes - Infer/propagate as many types throughout the expression
326 /// patterns as possible. Return true if all types are infered, false
327 /// otherwise. Throw an exception if a type contradiction is found.
328 bool InferAllTypes();
330 /// error - Throw an exception, prefixing it with information about this
332 void error(const std::string &Msg) const;
334 void print(std::ostream &OS) const;
338 TreePatternNode *ParseTreePattern(DagInit *DI);
342 class DAGInstruction {
343 TreePattern *Pattern;
344 std::vector<Record*> Results;
345 std::vector<Record*> Operands;
346 std::vector<Record*> ImpResults;
347 std::vector<Record*> ImpOperands;
348 TreePatternNode *ResultPattern;
350 DAGInstruction(TreePattern *TP,
351 const std::vector<Record*> &results,
352 const std::vector<Record*> &operands,
353 const std::vector<Record*> &impresults,
354 const std::vector<Record*> &impoperands)
355 : Pattern(TP), Results(results), Operands(operands),
356 ImpResults(impresults), ImpOperands(impoperands),
359 TreePattern *getPattern() const { return Pattern; }
360 unsigned getNumResults() const { return Results.size(); }
361 unsigned getNumOperands() const { return Operands.size(); }
362 unsigned getNumImpResults() const { return ImpResults.size(); }
363 unsigned getNumImpOperands() const { return ImpOperands.size(); }
365 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
367 Record *getResult(unsigned RN) const {
368 assert(RN < Results.size());
372 Record *getOperand(unsigned ON) const {
373 assert(ON < Operands.size());
377 Record *getImpResult(unsigned RN) const {
378 assert(RN < ImpResults.size());
379 return ImpResults[RN];
382 Record *getImpOperand(unsigned ON) const {
383 assert(ON < ImpOperands.size());
384 return ImpOperands[ON];
387 TreePatternNode *getResultPattern() const { return ResultPattern; }
390 /// PatternToMatch - Used by DAGISelEmitter to keep tab of patterns processed
392 struct PatternToMatch {
393 PatternToMatch(ListInit *preds, TreePatternNode *src, TreePatternNode *dst):
394 Predicates(preds), SrcPattern(src), DstPattern(dst) {};
396 ListInit *Predicates; // Top level predicate conditions to match.
397 TreePatternNode *SrcPattern; // Source pattern to match.
398 TreePatternNode *DstPattern; // Resulting pattern.
400 ListInit *getPredicates() const { return Predicates; }
401 TreePatternNode *getSrcPattern() const { return SrcPattern; }
402 TreePatternNode *getDstPattern() const { return DstPattern; }
405 /// DAGISelEmitter - The top-level class which coordinates construction
406 /// and emission of the instruction selector.
408 class DAGISelEmitter : public TableGenBackend {
410 RecordKeeper &Records;
411 CodeGenTarget Target;
413 std::map<Record*, SDNodeInfo> SDNodes;
414 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
415 std::map<Record*, ComplexPattern> ComplexPatterns;
416 std::map<Record*, TreePattern*> PatternFragments;
417 std::map<Record*, DAGInstruction> Instructions;
419 /// PatternsToMatch - All of the things we are matching on the DAG. The first
420 /// value is the pattern to match, the second pattern is the result to
422 std::vector<PatternToMatch> PatternsToMatch;
424 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
426 // run - Output the isel, returning true on failure.
427 void run(std::ostream &OS);
429 const CodeGenTarget &getTargetInfo() const { return Target; }
431 Record *getSDNodeNamed(const std::string &Name) const;
433 const SDNodeInfo &getSDNodeInfo(Record *R) const {
434 assert(SDNodes.count(R) && "Unknown node!");
435 return SDNodes.find(R)->second;
438 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
439 assert(SDNodeXForms.count(R) && "Invalid transform!");
440 return SDNodeXForms.find(R)->second;
443 const ComplexPattern &getComplexPattern(Record *R) const {
444 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
445 return ComplexPatterns.find(R)->second;
448 TreePattern *getPatternFragment(Record *R) const {
449 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
450 return PatternFragments.find(R)->second;
453 const DAGInstruction &getInstruction(Record *R) const {
454 assert(Instructions.count(R) && "Unknown instruction!");
455 return Instructions.find(R)->second;
459 void ParseNodeInfo();
460 void ParseNodeTransforms(std::ostream &OS);
461 void ParseComplexPatterns();
462 void ParsePatternFragments(std::ostream &OS);
463 void ParseInstructions();
464 void ParsePatterns();
465 void GenerateVariants();
466 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
467 std::map<std::string,
468 TreePatternNode*> &InstInputs,
469 std::map<std::string, Record*> &InstResults,
470 std::vector<Record*> &InstImpInputs,
471 std::vector<Record*> &InstImpResults);
472 void GenerateCodeForPattern(PatternToMatch &Pattern,
473 std::vector<std::pair<bool, std::string> > &GeneratedCode,
474 std::set<std::string> &GeneratedDecl,
476 void EmitPatterns(std::vector<std::pair<PatternToMatch*,
477 std::vector<std::pair<bool, std::string> > > > &Patterns,
478 unsigned Indent, std::ostream &OS);
479 void EmitInstructionSelector(std::ostream &OS);
482 } // End llvm namespace