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 /// SDTypeConstraint - This is a discriminated union of constraints,
31 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
32 struct SDTypeConstraint {
33 SDTypeConstraint(Record *R);
35 unsigned OperandNo; // The operand # this constraint applies to.
37 SDTCisVT, SDTCisInt, SDTCisFP, SDTCisSameAs, SDTCisVTSmallerThanOp
40 union { // The discriminated union.
45 unsigned OtherOperandNum;
48 unsigned OtherOperandNum;
49 } SDTCisVTSmallerThanOp_Info;
52 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
53 /// constraint to the nodes operands. This returns true if it makes a
54 /// change, false otherwise. If a type contradiction is found, throw an
56 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
57 TreePattern &TP) const;
59 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
60 /// N, which has NumResults results.
61 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
62 unsigned NumResults) const;
65 /// SDNodeInfo - One of these records is created for each SDNode instance in
66 /// the target .td file. This represents the various dag nodes we will be
71 std::string SDClassName;
75 std::vector<SDTypeConstraint> TypeConstraints;
77 SDNodeInfo(Record *R); // Parse the specified record.
79 unsigned getNumResults() const { return NumResults; }
80 int getNumOperands() const { return NumOperands; }
81 Record *getRecord() const { return Def; }
82 const std::string &getEnumName() const { return EnumName; }
83 const std::string &getSDClassName() const { return SDClassName; }
85 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
86 return TypeConstraints;
89 // SelectionDAG node properties.
90 enum SDNP { SDNPCommutative };
92 /// hasProperty - Return true if this node has the specified property.
94 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
96 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
97 /// constraints for this node to the operands of the node. This returns
98 /// true if it makes a change, false otherwise. If a type contradiction is
99 /// found, throw an exception.
100 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
101 bool MadeChange = false;
102 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
103 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
108 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
109 /// patterns), and as such should be ref counted. We currently just leak all
110 /// TreePatternNode objects!
111 class TreePatternNode {
112 /// The inferred type for this node, or MVT::LAST_VALUETYPE if it hasn't
113 /// been determined yet.
116 /// Operator - The Record for the operator if this is an interior node (not
120 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
124 /// Name - The name given to this node with the :$foo notation.
128 /// PredicateFn - The predicate function to execute on this node to check
129 /// for a match. If this string is empty, no predicate is involved.
130 std::string PredicateFn;
132 /// TransformFn - The transformation function to execute on this node before
133 /// it can be substituted into the resulting instruction on a pattern match.
136 std::vector<TreePatternNode*> Children;
138 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
139 : Ty(MVT::LAST_VALUETYPE), Operator(Op), Val(0), TransformFn(0),
141 TreePatternNode(Init *val) // leaf ctor
142 : Ty(MVT::LAST_VALUETYPE), Operator(0), Val(val), TransformFn(0) {}
145 const std::string &getName() const { return Name; }
146 void setName(const std::string &N) { Name = N; }
148 bool isLeaf() const { return Val != 0; }
149 bool hasTypeSet() const { return Ty != MVT::LAST_VALUETYPE; }
150 MVT::ValueType getType() const { return Ty; }
151 void setType(MVT::ValueType VT) { Ty = VT; }
153 Init *getLeafValue() const { assert(isLeaf()); return Val; }
154 Record *getOperator() const { assert(!isLeaf()); return Operator; }
156 unsigned getNumChildren() const { return Children.size(); }
157 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
158 void setChild(unsigned i, TreePatternNode *N) {
162 const std::string &getPredicateFn() const { return PredicateFn; }
163 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
165 Record *getTransformFn() const { return TransformFn; }
166 void setTransformFn(Record *Fn) { TransformFn = Fn; }
168 void print(std::ostream &OS) const;
171 public: // Higher level manipulation routines.
173 /// clone - Return a new copy of this tree.
175 TreePatternNode *clone() const;
177 /// SubstituteFormalArguments - Replace the formal arguments in this tree
178 /// with actual values specified by ArgMap.
179 void SubstituteFormalArguments(std::map<std::string,
180 TreePatternNode*> &ArgMap);
182 /// InlinePatternFragments - If this pattern refers to any pattern
183 /// fragments, inline them into place, giving us a pattern without any
184 /// PatFrag references.
185 TreePatternNode *InlinePatternFragments(TreePattern &TP);
187 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
188 /// this node and its children in the tree. This returns true if it makes a
189 /// change, false otherwise. If a type contradiction is found, throw an
191 bool ApplyTypeConstraints(TreePattern &TP);
193 /// UpdateNodeType - Set the node type of N to VT if VT contains
194 /// information. If N already contains a conflicting type, then throw an
195 /// exception. This returns true if any information was updated.
197 bool UpdateNodeType(MVT::ValueType VT, TreePattern &TP);
199 /// ContainsUnresolvedType - Return true if this tree contains any
200 /// unresolved types.
201 bool ContainsUnresolvedType() const {
202 if (Ty == MVT::LAST_VALUETYPE) return true;
203 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
204 if (getChild(i)->ContainsUnresolvedType()) return true;
208 /// canPatternMatch - Return false if it is impossible for this pattern to
209 /// match on this target.
210 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
214 /// TreePattern - Represent a pattern, used for instructions, pattern
218 /// Trees - The list of pattern trees which corresponds to this pattern.
219 /// Note that PatFrag's only have a single tree.
221 std::vector<TreePatternNode*> Trees;
223 /// TheRecord - The actual TableGen record corresponding to this pattern.
227 /// Args - This is a list of all of the arguments to this pattern (for
228 /// PatFrag patterns), which are the 'node' markers in this pattern.
229 std::vector<std::string> Args;
231 /// ISE - the DAG isel emitter coordinating this madness.
236 /// TreePattern constructor - Parse the specified DagInits into the
238 TreePattern(Record *TheRec, ListInit *RawPat, DAGISelEmitter &ise);
239 TreePattern(Record *TheRec, DagInit *Pat, DAGISelEmitter &ise);
240 TreePattern(Record *TheRec, TreePatternNode *Pat, DAGISelEmitter &ise);
242 /// getTrees - Return the tree patterns which corresponds to this pattern.
244 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
245 unsigned getNumTrees() const { return Trees.size(); }
246 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
247 TreePatternNode *getOnlyTree() const {
248 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
252 /// getRecord - Return the actual TableGen record corresponding to this
255 Record *getRecord() const { return TheRecord; }
257 unsigned getNumArgs() const { return Args.size(); }
258 const std::string &getArgName(unsigned i) const {
259 assert(i < Args.size() && "Argument reference out of range!");
262 std::vector<std::string> &getArgList() { return Args; }
264 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
266 /// InlinePatternFragments - If this pattern refers to any pattern
267 /// fragments, inline them into place, giving us a pattern without any
268 /// PatFrag references.
269 void InlinePatternFragments() {
270 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
271 Trees[i] = Trees[i]->InlinePatternFragments(*this);
274 /// InferAllTypes - Infer/propagate as many types throughout the expression
275 /// patterns as possible. Return true if all types are infered, false
276 /// otherwise. Throw an exception if a type contradiction is found.
277 bool InferAllTypes();
279 /// error - Throw an exception, prefixing it with information about this
281 void error(const std::string &Msg) const;
283 void print(std::ostream &OS) const;
287 MVT::ValueType getIntrinsicType(Record *R) const;
288 TreePatternNode *ParseTreePattern(DagInit *DI);
292 class DAGInstruction {
293 TreePattern *Pattern;
295 unsigned NumOperands;
296 std::vector<MVT::ValueType> ResultTypes;
297 std::vector<MVT::ValueType> OperandTypes;
298 TreePatternNode *ResultPattern;
300 DAGInstruction(TreePattern *TP,
301 const std::vector<MVT::ValueType> &resultTypes,
302 const std::vector<MVT::ValueType> &operandTypes)
303 : Pattern(TP), ResultTypes(resultTypes), OperandTypes(operandTypes),
306 TreePattern *getPattern() const { return Pattern; }
307 unsigned getNumResults() const { return ResultTypes.size(); }
308 unsigned getNumOperands() const { return OperandTypes.size(); }
310 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
312 MVT::ValueType getResultType(unsigned RN) const {
313 assert(RN < ResultTypes.size());
314 return ResultTypes[RN];
317 MVT::ValueType getOperandType(unsigned ON) const {
318 assert(ON < OperandTypes.size());
319 return OperandTypes[ON];
321 TreePatternNode *getResultPattern() const { return ResultPattern; }
325 /// InstrSelectorEmitter - The top-level class which coordinates construction
326 /// and emission of the instruction selector.
328 class DAGISelEmitter : public TableGenBackend {
330 typedef std::pair<TreePatternNode*, TreePatternNode*> PatternToMatch;
332 RecordKeeper &Records;
333 CodeGenTarget Target;
335 std::map<Record*, SDNodeInfo> SDNodes;
336 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
337 std::map<Record*, TreePattern*> PatternFragments;
338 std::map<Record*, DAGInstruction> Instructions;
340 /// PatternsToMatch - All of the things we are matching on the DAG. The first
341 /// value is the pattern to match, the second pattern is the result to
343 std::vector<PatternToMatch> PatternsToMatch;
345 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
347 // run - Output the isel, returning true on failure.
348 void run(std::ostream &OS);
350 const SDNodeInfo &getSDNodeInfo(Record *R) const {
351 assert(SDNodes.count(R) && "Unknown node!");
352 return SDNodes.find(R)->second;
355 TreePattern *getPatternFragment(Record *R) const {
356 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
357 return PatternFragments.find(R)->second;
360 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
361 assert(SDNodeXForms.count(R) && "Invalid transform!");
362 return SDNodeXForms.find(R)->second;
365 const DAGInstruction &getInstruction(Record *R) const {
366 assert(Instructions.count(R) && "Unknown instruction!");
367 return Instructions.find(R)->second;
371 void ParseNodeInfo();
372 void ParseNodeTransforms(std::ostream &OS);
373 void ParsePatternFragments(std::ostream &OS);
374 void ParseInstructions();
375 void ParsePatterns();
376 void GenerateVariants();
377 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
378 std::map<std::string,
379 TreePatternNode*> &InstInputs,
380 std::map<std::string, Record*> &InstResults);
381 void EmitMatchForPattern(TreePatternNode *N, const std::string &RootName,
382 std::map<std::string,std::string> &VarMap,
383 unsigned PatternNo, std::ostream &OS);
384 unsigned CodeGenPatternResult(TreePatternNode *N, unsigned &Ctr,
385 std::map<std::string,std::string> &VariableMap,
387 void EmitCodeForPattern(PatternToMatch &Pattern, std::ostream &OS);
388 void EmitInstructionSelector(std::ostream &OS);
391 } // End llvm namespace