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"
27 class TreePatternNode;
30 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
31 /// that we use as lattice values during type inferrence.
33 enum DAGISelGenValueType {
34 isFP = MVT::LAST_VALUETYPE,
40 /// SDTypeConstraint - This is a discriminated union of constraints,
41 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
42 struct SDTypeConstraint {
43 SDTypeConstraint(Record *R);
45 unsigned OperandNo; // The operand # this constraint applies to.
47 SDTCisVT, SDTCisInt, SDTCisFP, SDTCisSameAs, SDTCisVTSmallerThanOp,
51 union { // The discriminated union.
56 unsigned OtherOperandNum;
59 unsigned OtherOperandNum;
60 } SDTCisVTSmallerThanOp_Info;
62 unsigned BigOperandNum;
63 } SDTCisOpSmallerThanOp_Info;
66 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
67 /// constraint to the nodes operands. This returns true if it makes a
68 /// change, false otherwise. If a type contradiction is found, throw an
70 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
71 TreePattern &TP) const;
73 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
74 /// N, which has NumResults results.
75 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
76 unsigned NumResults) const;
79 /// SDNodeInfo - One of these records is created for each SDNode instance in
80 /// the target .td file. This represents the various dag nodes we will be
85 std::string SDClassName;
89 std::vector<SDTypeConstraint> TypeConstraints;
91 SDNodeInfo(Record *R); // Parse the specified record.
93 unsigned getNumResults() const { return NumResults; }
94 int getNumOperands() const { return NumOperands; }
95 Record *getRecord() const { return Def; }
96 const std::string &getEnumName() const { return EnumName; }
97 const std::string &getSDClassName() const { return SDClassName; }
99 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
100 return TypeConstraints;
103 // SelectionDAG node properties.
104 enum SDNP { SDNPCommutative, SDNPAssociative };
106 /// hasProperty - Return true if this node has the specified property.
108 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
110 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
111 /// constraints for this node to the operands of the node. This returns
112 /// true if it makes a change, false otherwise. If a type contradiction is
113 /// found, throw an exception.
114 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
115 bool MadeChange = false;
116 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
117 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
122 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
123 /// patterns), and as such should be ref counted. We currently just leak all
124 /// TreePatternNode objects!
125 class TreePatternNode {
126 /// The inferred type for this node, or MVT::LAST_VALUETYPE if it hasn't
127 /// been determined yet.
130 /// Operator - The Record for the operator if this is an interior node (not
134 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
138 /// Name - The name given to this node with the :$foo notation.
142 /// PredicateFn - The predicate function to execute on this node to check
143 /// for a match. If this string is empty, no predicate is involved.
144 std::string PredicateFn;
146 /// TransformFn - The transformation function to execute on this node before
147 /// it can be substituted into the resulting instruction on a pattern match.
150 std::vector<TreePatternNode*> Children;
152 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
153 : Ty(MVT::isUnknown), Operator(Op), Val(0), TransformFn(0),
155 TreePatternNode(Init *val) // leaf ctor
156 : Ty(MVT::isUnknown), Operator(0), Val(val), TransformFn(0) {}
159 const std::string &getName() const { return Name; }
160 void setName(const std::string &N) { Name = N; }
162 bool isLeaf() const { return Val != 0; }
163 bool hasTypeSet() const { return Ty < MVT::LAST_VALUETYPE; }
164 bool isTypeCompletelyUnknown() const {
165 return Ty == MVT::isUnknown;
167 MVT::ValueType getType() const {
168 assert(hasTypeSet() && "Doesn't have a type yet!");
169 return (MVT::ValueType)Ty;
171 unsigned char getExtType() const { return Ty; }
172 void setType(unsigned char VT) { Ty = VT; }
174 Init *getLeafValue() const { assert(isLeaf()); return Val; }
175 Record *getOperator() const { assert(!isLeaf()); return Operator; }
177 unsigned getNumChildren() const { return Children.size(); }
178 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
179 void setChild(unsigned i, TreePatternNode *N) {
183 const std::string &getPredicateFn() const { return PredicateFn; }
184 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
186 Record *getTransformFn() const { return TransformFn; }
187 void setTransformFn(Record *Fn) { TransformFn = Fn; }
189 void print(std::ostream &OS) const;
192 public: // Higher level manipulation routines.
194 /// clone - Return a new copy of this tree.
196 TreePatternNode *clone() const;
198 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
199 /// the specified node. For this comparison, all of the state of the node
200 /// is considered, except for the assigned name. Nodes with differing names
201 /// that are otherwise identical are considered isomorphic.
202 bool isIsomorphicTo(const TreePatternNode *N) const;
204 /// SubstituteFormalArguments - Replace the formal arguments in this tree
205 /// with actual values specified by ArgMap.
206 void SubstituteFormalArguments(std::map<std::string,
207 TreePatternNode*> &ArgMap);
209 /// InlinePatternFragments - If this pattern refers to any pattern
210 /// fragments, inline them into place, giving us a pattern without any
211 /// PatFrag references.
212 TreePatternNode *InlinePatternFragments(TreePattern &TP);
214 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
215 /// this node and its children in the tree. This returns true if it makes a
216 /// change, false otherwise. If a type contradiction is found, throw an
218 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
220 /// UpdateNodeType - Set the node type of N to VT if VT contains
221 /// information. If N already contains a conflicting type, then throw an
222 /// exception. This returns true if any information was updated.
224 bool UpdateNodeType(unsigned char EVT, TreePattern &TP);
226 /// ContainsUnresolvedType - Return true if this tree contains any
227 /// unresolved types.
228 bool ContainsUnresolvedType() const {
229 if (!hasTypeSet()) return true;
230 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
231 if (getChild(i)->ContainsUnresolvedType()) return true;
235 /// canPatternMatch - If it is impossible for this pattern to match on this
236 /// target, fill in Reason and return false. Otherwise, return true.
237 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
241 /// TreePattern - Represent a pattern, used for instructions, pattern
245 /// Trees - The list of pattern trees which corresponds to this pattern.
246 /// Note that PatFrag's only have a single tree.
248 std::vector<TreePatternNode*> Trees;
250 /// TheRecord - The actual TableGen record corresponding to this pattern.
254 /// Args - This is a list of all of the arguments to this pattern (for
255 /// PatFrag patterns), which are the 'node' markers in this pattern.
256 std::vector<std::string> Args;
258 /// ISE - the DAG isel emitter coordinating this madness.
262 /// isInputPattern - True if this is an input pattern, something to match.
263 /// False if this is an output pattern, something to emit.
267 /// TreePattern constructor - Parse the specified DagInits into the
269 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
270 DAGISelEmitter &ise);
271 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
272 DAGISelEmitter &ise);
273 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
274 DAGISelEmitter &ise);
276 /// getTrees - Return the tree patterns which corresponds to this pattern.
278 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
279 unsigned getNumTrees() const { return Trees.size(); }
280 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
281 TreePatternNode *getOnlyTree() const {
282 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
286 /// getRecord - Return the actual TableGen record corresponding to this
289 Record *getRecord() const { return TheRecord; }
291 unsigned getNumArgs() const { return Args.size(); }
292 const std::string &getArgName(unsigned i) const {
293 assert(i < Args.size() && "Argument reference out of range!");
296 std::vector<std::string> &getArgList() { return Args; }
298 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
300 /// InlinePatternFragments - If this pattern refers to any pattern
301 /// fragments, inline them into place, giving us a pattern without any
302 /// PatFrag references.
303 void InlinePatternFragments() {
304 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
305 Trees[i] = Trees[i]->InlinePatternFragments(*this);
308 /// InferAllTypes - Infer/propagate as many types throughout the expression
309 /// patterns as possible. Return true if all types are infered, false
310 /// otherwise. Throw an exception if a type contradiction is found.
311 bool InferAllTypes();
313 /// error - Throw an exception, prefixing it with information about this
315 void error(const std::string &Msg) const;
317 void print(std::ostream &OS) const;
321 TreePatternNode *ParseTreePattern(DagInit *DI);
325 class DAGInstruction {
326 TreePattern *Pattern;
328 unsigned NumOperands;
329 std::vector<MVT::ValueType> ResultTypes;
330 std::vector<MVT::ValueType> OperandTypes;
331 TreePatternNode *ResultPattern;
333 DAGInstruction(TreePattern *TP,
334 const std::vector<MVT::ValueType> &resultTypes,
335 const std::vector<MVT::ValueType> &operandTypes)
336 : Pattern(TP), ResultTypes(resultTypes), OperandTypes(operandTypes),
339 TreePattern *getPattern() const { return Pattern; }
340 unsigned getNumResults() const { return ResultTypes.size(); }
341 unsigned getNumOperands() const { return OperandTypes.size(); }
343 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
345 MVT::ValueType getResultType(unsigned RN) const {
346 assert(RN < ResultTypes.size());
347 return ResultTypes[RN];
350 MVT::ValueType getOperandType(unsigned ON) const {
351 assert(ON < OperandTypes.size());
352 return OperandTypes[ON];
354 TreePatternNode *getResultPattern() const { return ResultPattern; }
358 /// InstrSelectorEmitter - The top-level class which coordinates construction
359 /// and emission of the instruction selector.
361 class DAGISelEmitter : public TableGenBackend {
363 typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
365 RecordKeeper &Records;
366 CodeGenTarget Target;
368 std::map<Record*, SDNodeInfo> SDNodes;
369 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
370 std::map<Record*, TreePattern*> PatternFragments;
371 std::map<Record*, DAGInstruction> Instructions;
373 /// PatternsToMatch - All of the things we are matching on the DAG. The first
374 /// value is the pattern to match, the second pattern is the result to
376 std::vector<PatternToMatch> PatternsToMatch;
378 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
380 // run - Output the isel, returning true on failure.
381 void run(std::ostream &OS);
383 const CodeGenTarget &getTargetInfo() const { return Target; }
385 const SDNodeInfo &getSDNodeInfo(Record *R) const {
386 assert(SDNodes.count(R) && "Unknown node!");
387 return SDNodes.find(R)->second;
390 TreePattern *getPatternFragment(Record *R) const {
391 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
392 return PatternFragments.find(R)->second;
395 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
396 assert(SDNodeXForms.count(R) && "Invalid transform!");
397 return SDNodeXForms.find(R)->second;
400 const DAGInstruction &getInstruction(Record *R) const {
401 assert(Instructions.count(R) && "Unknown instruction!");
402 return Instructions.find(R)->second;
406 void ParseNodeInfo();
407 void ParseNodeTransforms(std::ostream &OS);
408 void ParsePatternFragments(std::ostream &OS);
409 void ParseInstructions();
410 void ParsePatterns();
411 void GenerateVariants();
412 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
413 std::map<std::string,
414 TreePatternNode*> &InstInputs,
415 std::map<std::string, Record*> &InstResults);
416 void EmitMatchForPattern(TreePatternNode *N, const std::string &RootName,
417 std::map<std::string,std::string> &VarMap,
418 unsigned PatternNo, std::ostream &OS);
419 unsigned CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
420 std::map<std::string,std::string> &VariableMap,
421 std::ostream &OS, bool isRoot = false);
422 void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
423 void EmitInstructionSelector(std::ostream &OS);
426 } // End llvm namespace