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;
31 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
32 /// that we use as lattice values during type inferrence.
34 enum DAGISelGenValueType {
35 isFP = MVT::LAST_VALUETYPE,
41 /// SDTypeConstraint - This is a discriminated union of constraints,
42 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
43 struct SDTypeConstraint {
44 SDTypeConstraint(Record *R);
46 unsigned OperandNo; // The operand # this constraint applies to.
48 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
49 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp
52 union { // The discriminated union.
57 unsigned OtherOperandNum;
60 unsigned OtherOperandNum;
61 } SDTCisVTSmallerThanOp_Info;
63 unsigned BigOperandNum;
64 } SDTCisOpSmallerThanOp_Info;
67 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
68 /// constraint to the nodes operands. This returns true if it makes a
69 /// change, false otherwise. If a type contradiction is found, throw an
71 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
72 TreePattern &TP) const;
74 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
75 /// N, which has NumResults results.
76 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
77 unsigned NumResults) const;
80 /// SDNodeInfo - One of these records is created for each SDNode instance in
81 /// the target .td file. This represents the various dag nodes we will be
86 std::string SDClassName;
90 std::vector<SDTypeConstraint> TypeConstraints;
92 SDNodeInfo(Record *R); // Parse the specified record.
94 unsigned getNumResults() const { return NumResults; }
95 int getNumOperands() const { return NumOperands; }
96 Record *getRecord() const { return Def; }
97 const std::string &getEnumName() const { return EnumName; }
98 const std::string &getSDClassName() const { return SDClassName; }
100 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
101 return TypeConstraints;
104 // SelectionDAG node properties.
105 enum SDNP { SDNPCommutative, SDNPAssociative, SDNPHasChain,
106 SDNPOutFlag, SDNPInFlag, SDNPOptInFlag };
108 /// hasProperty - Return true if this node has the specified property.
110 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
112 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
113 /// constraints for this node to the operands of the node. This returns
114 /// true if it makes a change, false otherwise. If a type contradiction is
115 /// found, throw an exception.
116 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
117 bool MadeChange = false;
118 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
119 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
124 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
125 /// patterns), and as such should be ref counted. We currently just leak all
126 /// TreePatternNode objects!
127 class TreePatternNode {
128 /// The inferred type for this node, or MVT::isUnknown if it hasn't
129 /// been determined yet.
130 std::vector<unsigned char> Types;
132 /// Operator - The Record for the operator if this is an interior node (not
136 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
140 /// Name - The name given to this node with the :$foo notation.
144 /// PredicateFn - The predicate function to execute on this node to check
145 /// for a match. If this string is empty, no predicate is involved.
146 std::string PredicateFn;
148 /// TransformFn - The transformation function to execute on this node before
149 /// it can be substituted into the resulting instruction on a pattern match.
152 std::vector<TreePatternNode*> Children;
154 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
155 : Types(), Operator(Op), Val(0), TransformFn(0),
156 Children(Ch) { Types.push_back(MVT::isUnknown); }
157 TreePatternNode(Init *val) // leaf ctor
158 : Types(), Operator(0), Val(val), TransformFn(0) { Types.push_back(MVT::isUnknown); }
161 const std::string &getName() const { return Name; }
162 void setName(const std::string &N) { Name = N; }
164 bool isLeaf() const { return Val != 0; }
165 bool hasTypeSet() const { return Types[0] < MVT::LAST_VALUETYPE; }
166 bool isTypeCompletelyUnknown() const {
167 return Types[0] == MVT::isUnknown;
169 MVT::ValueType getTypeNum(unsigned Num) const {
170 assert(hasTypeSet() && "Doesn't have a type yet!");
171 assert(Types.size() > Num && "Type num out of range!");
172 return (MVT::ValueType)Types[Num];
174 unsigned char getExtTypeNum(unsigned Num) const {
175 assert(Types.size() > Num && "Extended type num out of range!");
178 const std::vector<unsigned char> &getExtTypes() const { return Types; }
179 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
180 void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
182 Init *getLeafValue() const { assert(isLeaf()); return Val; }
183 Record *getOperator() const { assert(!isLeaf()); return Operator; }
185 unsigned getNumChildren() const { return Children.size(); }
186 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
187 void setChild(unsigned i, TreePatternNode *N) {
192 const std::string &getPredicateFn() const { return PredicateFn; }
193 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
195 Record *getTransformFn() const { return TransformFn; }
196 void setTransformFn(Record *Fn) { TransformFn = Fn; }
198 void print(std::ostream &OS) const;
201 public: // Higher level manipulation routines.
203 /// clone - Return a new copy of this tree.
205 TreePatternNode *clone() const;
207 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
208 /// the specified node. For this comparison, all of the state of the node
209 /// is considered, except for the assigned name. Nodes with differing names
210 /// that are otherwise identical are considered isomorphic.
211 bool isIsomorphicTo(const TreePatternNode *N) const;
213 /// SubstituteFormalArguments - Replace the formal arguments in this tree
214 /// with actual values specified by ArgMap.
215 void SubstituteFormalArguments(std::map<std::string,
216 TreePatternNode*> &ArgMap);
218 /// InlinePatternFragments - If this pattern refers to any pattern
219 /// fragments, inline them into place, giving us a pattern without any
220 /// PatFrag references.
221 TreePatternNode *InlinePatternFragments(TreePattern &TP);
223 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
224 /// this node and its children in the tree. This returns true if it makes a
225 /// change, false otherwise. If a type contradiction is found, throw an
227 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
229 /// UpdateNodeType - Set the node type of N to VT if VT contains
230 /// information. If N already contains a conflicting type, then throw an
231 /// exception. This returns true if any information was updated.
233 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
235 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
236 std::vector<unsigned char> ExtVTs(1, ExtVT);
237 return UpdateNodeType(ExtVTs, TP);
240 /// ContainsUnresolvedType - Return true if this tree contains any
241 /// unresolved types.
242 bool ContainsUnresolvedType() const {
243 if (!hasTypeSet()) return true;
244 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
245 if (getChild(i)->ContainsUnresolvedType()) return true;
249 /// canPatternMatch - If it is impossible for this pattern to match on this
250 /// target, fill in Reason and return false. Otherwise, return true.
251 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
255 /// TreePattern - Represent a pattern, used for instructions, pattern
259 /// Trees - The list of pattern trees which corresponds to this pattern.
260 /// Note that PatFrag's only have a single tree.
262 std::vector<TreePatternNode*> Trees;
264 /// TheRecord - The actual TableGen record corresponding to this pattern.
268 /// Args - This is a list of all of the arguments to this pattern (for
269 /// PatFrag patterns), which are the 'node' markers in this pattern.
270 std::vector<std::string> Args;
272 /// ISE - the DAG isel emitter coordinating this madness.
276 /// isInputPattern - True if this is an input pattern, something to match.
277 /// False if this is an output pattern, something to emit.
281 /// TreePattern constructor - Parse the specified DagInits into the
283 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
284 DAGISelEmitter &ise);
285 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
286 DAGISelEmitter &ise);
287 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
288 DAGISelEmitter &ise);
290 /// getTrees - Return the tree patterns which corresponds to this pattern.
292 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
293 unsigned getNumTrees() const { return Trees.size(); }
294 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
295 TreePatternNode *getOnlyTree() const {
296 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
300 /// getRecord - Return the actual TableGen record corresponding to this
303 Record *getRecord() const { return TheRecord; }
305 unsigned getNumArgs() const { return Args.size(); }
306 const std::string &getArgName(unsigned i) const {
307 assert(i < Args.size() && "Argument reference out of range!");
310 std::vector<std::string> &getArgList() { return Args; }
312 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
314 /// InlinePatternFragments - If this pattern refers to any pattern
315 /// fragments, inline them into place, giving us a pattern without any
316 /// PatFrag references.
317 void InlinePatternFragments() {
318 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
319 Trees[i] = Trees[i]->InlinePatternFragments(*this);
322 /// InferAllTypes - Infer/propagate as many types throughout the expression
323 /// patterns as possible. Return true if all types are infered, false
324 /// otherwise. Throw an exception if a type contradiction is found.
325 bool InferAllTypes();
327 /// error - Throw an exception, prefixing it with information about this
329 void error(const std::string &Msg) const;
331 void print(std::ostream &OS) const;
335 TreePatternNode *ParseTreePattern(DagInit *DI);
339 class DAGInstruction {
340 TreePattern *Pattern;
341 std::vector<Record*> Results;
342 std::vector<Record*> Operands;
343 std::vector<Record*> ImpResults;
344 std::vector<Record*> ImpOperands;
345 TreePatternNode *ResultPattern;
347 DAGInstruction(TreePattern *TP,
348 const std::vector<Record*> &results,
349 const std::vector<Record*> &operands,
350 const std::vector<Record*> &impresults,
351 const std::vector<Record*> &impoperands)
352 : Pattern(TP), Results(results), Operands(operands),
353 ImpResults(impresults), ImpOperands(impoperands),
356 TreePattern *getPattern() const { return Pattern; }
357 unsigned getNumResults() const { return Results.size(); }
358 unsigned getNumOperands() const { return Operands.size(); }
359 unsigned getNumImpResults() const { return ImpResults.size(); }
360 unsigned getNumImpOperands() const { return ImpOperands.size(); }
362 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
364 Record *getResult(unsigned RN) const {
365 assert(RN < Results.size());
369 Record *getOperand(unsigned ON) const {
370 assert(ON < Operands.size());
374 Record *getImpResult(unsigned RN) const {
375 assert(RN < ImpResults.size());
376 return ImpResults[RN];
379 Record *getImpOperand(unsigned ON) const {
380 assert(ON < ImpOperands.size());
381 return ImpOperands[ON];
384 TreePatternNode *getResultPattern() const { return ResultPattern; }
387 /// PatternToMatch - Used by DAGISelEmitter to keep tab of patterns processed
389 struct PatternToMatch {
390 PatternToMatch(ListInit *preds, TreePatternNode *src, TreePatternNode *dst):
391 Predicates(preds), SrcPattern(src), DstPattern(dst) {};
393 ListInit *Predicates; // Top level predicate conditions to match.
394 TreePatternNode *SrcPattern; // Source pattern to match.
395 TreePatternNode *DstPattern; // Resulting pattern.
397 ListInit *getPredicates() const { return Predicates; }
398 TreePatternNode *getSrcPattern() const { return SrcPattern; }
399 TreePatternNode *getDstPattern() const { return DstPattern; }
402 /// DAGISelEmitter - The top-level class which coordinates construction
403 /// and emission of the instruction selector.
405 class DAGISelEmitter : public TableGenBackend {
407 //typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
409 RecordKeeper &Records;
410 CodeGenTarget Target;
412 std::map<Record*, SDNodeInfo> SDNodes;
413 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
414 std::map<Record*, ComplexPattern> ComplexPatterns;
415 std::map<Record*, TreePattern*> PatternFragments;
416 std::map<Record*, DAGInstruction> Instructions;
418 /// PatternsToMatch - All of the things we are matching on the DAG. The first
419 /// value is the pattern to match, the second pattern is the result to
421 std::vector<PatternToMatch> PatternsToMatch;
423 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
425 // run - Output the isel, returning true on failure.
426 void run(std::ostream &OS);
428 const CodeGenTarget &getTargetInfo() const { return Target; }
430 Record *getSDNodeNamed(const std::string &Name) const;
432 const SDNodeInfo &getSDNodeInfo(Record *R) const {
433 assert(SDNodes.count(R) && "Unknown node!");
434 return SDNodes.find(R)->second;
437 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
438 assert(SDNodeXForms.count(R) && "Invalid transform!");
439 return SDNodeXForms.find(R)->second;
442 const ComplexPattern &getComplexPattern(Record *R) const {
443 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
444 return ComplexPatterns.find(R)->second;
447 TreePattern *getPatternFragment(Record *R) const {
448 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
449 return PatternFragments.find(R)->second;
452 const DAGInstruction &getInstruction(Record *R) const {
453 assert(Instructions.count(R) && "Unknown instruction!");
454 return Instructions.find(R)->second;
458 void ParseNodeInfo();
459 void ParseNodeTransforms(std::ostream &OS);
460 void ParseComplexPatterns();
461 void ParsePatternFragments(std::ostream &OS);
462 void ParseInstructions();
463 void ParsePatterns();
464 void GenerateVariants();
465 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
466 std::map<std::string,
467 TreePatternNode*> &InstInputs,
468 std::map<std::string, Record*> &InstResults,
469 std::vector<Record*> &InstImpInputs,
470 std::vector<Record*> &InstImpResults);
471 void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
472 void EmitInstructionSelector(std::ostream &OS);
475 } // End llvm namespace