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"
19 #include "CodeGenIntrinsics.h"
29 class TreePatternNode;
33 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
34 /// that we use as lattice values during type inferrence.
36 enum DAGISelGenValueType {
37 isFP = MVT::LAST_VALUETYPE,
43 /// SDTypeConstraint - This is a discriminated union of constraints,
44 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
45 struct SDTypeConstraint {
46 SDTypeConstraint(Record *R);
48 unsigned OperandNo; // The operand # this constraint applies to.
50 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
51 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize
54 union { // The discriminated union.
59 unsigned OtherOperandNum;
62 unsigned OtherOperandNum;
63 } SDTCisVTSmallerThanOp_Info;
65 unsigned BigOperandNum;
66 } SDTCisOpSmallerThanOp_Info;
68 unsigned OtherOperandNum;
69 } SDTCisIntVectorOfSameSize_Info;
72 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
73 /// constraint to the nodes operands. This returns true if it makes a
74 /// change, false otherwise. If a type contradiction is found, throw an
76 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
77 TreePattern &TP) const;
79 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
80 /// N, which has NumResults results.
81 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
82 unsigned NumResults) const;
85 /// SDNodeInfo - One of these records is created for each SDNode instance in
86 /// the target .td file. This represents the various dag nodes we will be
91 std::string SDClassName;
95 std::vector<SDTypeConstraint> TypeConstraints;
97 SDNodeInfo(Record *R); // Parse the specified record.
99 unsigned getNumResults() const { return NumResults; }
100 int getNumOperands() const { return NumOperands; }
101 Record *getRecord() const { return Def; }
102 const std::string &getEnumName() const { return EnumName; }
103 const std::string &getSDClassName() const { return SDClassName; }
105 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
106 return TypeConstraints;
109 // SelectionDAG node properties.
110 enum SDNP { SDNPCommutative, SDNPAssociative, SDNPHasChain,
111 SDNPOutFlag, SDNPInFlag, SDNPOptInFlag };
113 /// hasProperty - Return true if this node has the specified property.
115 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
117 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
118 /// constraints for this node to the operands of the node. This returns
119 /// true if it makes a change, false otherwise. If a type contradiction is
120 /// found, throw an exception.
121 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
122 bool MadeChange = false;
123 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
124 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
129 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
130 /// patterns), and as such should be ref counted. We currently just leak all
131 /// TreePatternNode objects!
132 class TreePatternNode {
133 /// The inferred type for this node, or MVT::isUnknown if it hasn't
134 /// been determined yet.
135 std::vector<unsigned char> Types;
137 /// Operator - The Record for the operator if this is an interior node (not
141 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
145 /// Name - The name given to this node with the :$foo notation.
149 /// PredicateFn - The predicate function to execute on this node to check
150 /// for a match. If this string is empty, no predicate is involved.
151 std::string PredicateFn;
153 /// TransformFn - The transformation function to execute on this node before
154 /// it can be substituted into the resulting instruction on a pattern match.
157 std::vector<TreePatternNode*> Children;
159 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
160 : Types(), Operator(Op), Val(0), TransformFn(0),
161 Children(Ch) { Types.push_back(MVT::isUnknown); }
162 TreePatternNode(Init *val) // leaf ctor
163 : Types(), Operator(0), Val(val), TransformFn(0) {
164 Types.push_back(MVT::isUnknown);
168 const std::string &getName() const { return Name; }
169 void setName(const std::string &N) { Name = N; }
171 bool isLeaf() const { return Val != 0; }
172 bool hasTypeSet() const {
173 return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR);
175 bool isTypeCompletelyUnknown() const {
176 return Types[0] == MVT::isUnknown;
178 bool isTypeDynamicallyResolved() const {
179 return Types[0] == MVT::iPTR;
181 MVT::ValueType getTypeNum(unsigned Num) const {
182 assert(hasTypeSet() && "Doesn't have a type yet!");
183 assert(Types.size() > Num && "Type num out of range!");
184 return (MVT::ValueType)Types[Num];
186 unsigned char getExtTypeNum(unsigned Num) const {
187 assert(Types.size() > Num && "Extended type num out of range!");
190 const std::vector<unsigned char> &getExtTypes() const { return Types; }
191 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
192 void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
194 Init *getLeafValue() const { assert(isLeaf()); return Val; }
195 Record *getOperator() const { assert(!isLeaf()); return Operator; }
197 unsigned getNumChildren() const { return Children.size(); }
198 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
199 void setChild(unsigned i, TreePatternNode *N) {
204 const std::string &getPredicateFn() const { return PredicateFn; }
205 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
207 Record *getTransformFn() const { return TransformFn; }
208 void setTransformFn(Record *Fn) { TransformFn = Fn; }
210 void print(std::ostream &OS) const;
213 public: // Higher level manipulation routines.
215 /// clone - Return a new copy of this tree.
217 TreePatternNode *clone() const;
219 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
220 /// the specified node. For this comparison, all of the state of the node
221 /// is considered, except for the assigned name. Nodes with differing names
222 /// that are otherwise identical are considered isomorphic.
223 bool isIsomorphicTo(const TreePatternNode *N) const;
225 /// SubstituteFormalArguments - Replace the formal arguments in this tree
226 /// with actual values specified by ArgMap.
227 void SubstituteFormalArguments(std::map<std::string,
228 TreePatternNode*> &ArgMap);
230 /// InlinePatternFragments - If this pattern refers to any pattern
231 /// fragments, inline them into place, giving us a pattern without any
232 /// PatFrag references.
233 TreePatternNode *InlinePatternFragments(TreePattern &TP);
235 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
236 /// this node and its children in the tree. This returns true if it makes a
237 /// change, false otherwise. If a type contradiction is found, throw an
239 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
241 /// UpdateNodeType - Set the node type of N to VT if VT contains
242 /// information. If N already contains a conflicting type, then throw an
243 /// exception. This returns true if any information was updated.
245 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
247 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
248 std::vector<unsigned char> ExtVTs(1, ExtVT);
249 return UpdateNodeType(ExtVTs, TP);
252 /// ContainsUnresolvedType - Return true if this tree contains any
253 /// unresolved types.
254 bool ContainsUnresolvedType() const {
255 if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
256 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
257 if (getChild(i)->ContainsUnresolvedType()) return true;
261 /// canPatternMatch - If it is impossible for this pattern to match on this
262 /// target, fill in Reason and return false. Otherwise, return true.
263 bool canPatternMatch(std::string &Reason, DAGISelEmitter &ISE);
267 /// TreePattern - Represent a pattern, used for instructions, pattern
271 /// Trees - The list of pattern trees which corresponds to this pattern.
272 /// Note that PatFrag's only have a single tree.
274 std::vector<TreePatternNode*> Trees;
276 /// TheRecord - The actual TableGen record corresponding to this pattern.
280 /// Args - This is a list of all of the arguments to this pattern (for
281 /// PatFrag patterns), which are the 'node' markers in this pattern.
282 std::vector<std::string> Args;
284 /// ISE - the DAG isel emitter coordinating this madness.
288 /// isInputPattern - True if this is an input pattern, something to match.
289 /// False if this is an output pattern, something to emit.
293 /// TreePattern constructor - Parse the specified DagInits into the
295 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
296 DAGISelEmitter &ise);
297 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
298 DAGISelEmitter &ise);
299 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
300 DAGISelEmitter &ise);
302 /// getTrees - Return the tree patterns which corresponds to this pattern.
304 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
305 unsigned getNumTrees() const { return Trees.size(); }
306 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
307 TreePatternNode *getOnlyTree() const {
308 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
312 /// getRecord - Return the actual TableGen record corresponding to this
315 Record *getRecord() const { return TheRecord; }
317 unsigned getNumArgs() const { return Args.size(); }
318 const std::string &getArgName(unsigned i) const {
319 assert(i < Args.size() && "Argument reference out of range!");
322 std::vector<std::string> &getArgList() { return Args; }
324 DAGISelEmitter &getDAGISelEmitter() const { return ISE; }
326 /// InlinePatternFragments - If this pattern refers to any pattern
327 /// fragments, inline them into place, giving us a pattern without any
328 /// PatFrag references.
329 void InlinePatternFragments() {
330 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
331 Trees[i] = Trees[i]->InlinePatternFragments(*this);
334 /// InferAllTypes - Infer/propagate as many types throughout the expression
335 /// patterns as possible. Return true if all types are infered, false
336 /// otherwise. Throw an exception if a type contradiction is found.
337 bool InferAllTypes();
339 /// error - Throw an exception, prefixing it with information about this
341 void error(const std::string &Msg) const;
343 void print(std::ostream &OS) const;
347 TreePatternNode *ParseTreePattern(DagInit *DI);
351 class DAGInstruction {
352 TreePattern *Pattern;
353 std::vector<Record*> Results;
354 std::vector<Record*> Operands;
355 std::vector<Record*> ImpResults;
356 std::vector<Record*> ImpOperands;
357 TreePatternNode *ResultPattern;
359 DAGInstruction(TreePattern *TP,
360 const std::vector<Record*> &results,
361 const std::vector<Record*> &operands,
362 const std::vector<Record*> &impresults,
363 const std::vector<Record*> &impoperands)
364 : Pattern(TP), Results(results), Operands(operands),
365 ImpResults(impresults), ImpOperands(impoperands),
368 TreePattern *getPattern() const { return Pattern; }
369 unsigned getNumResults() const { return Results.size(); }
370 unsigned getNumOperands() const { return Operands.size(); }
371 unsigned getNumImpResults() const { return ImpResults.size(); }
372 unsigned getNumImpOperands() const { return ImpOperands.size(); }
374 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
376 Record *getResult(unsigned RN) const {
377 assert(RN < Results.size());
381 Record *getOperand(unsigned ON) const {
382 assert(ON < Operands.size());
386 Record *getImpResult(unsigned RN) const {
387 assert(RN < ImpResults.size());
388 return ImpResults[RN];
391 Record *getImpOperand(unsigned ON) const {
392 assert(ON < ImpOperands.size());
393 return ImpOperands[ON];
396 TreePatternNode *getResultPattern() const { return ResultPattern; }
399 /// PatternToMatch - Used by DAGISelEmitter to keep tab of patterns processed
401 struct PatternToMatch {
402 PatternToMatch(ListInit *preds,
403 TreePatternNode *src, TreePatternNode *dst,
404 unsigned complexity):
405 Predicates(preds), SrcPattern(src), DstPattern(dst),
406 AddedComplexity(complexity) {};
408 ListInit *Predicates; // Top level predicate conditions to match.
409 TreePatternNode *SrcPattern; // Source pattern to match.
410 TreePatternNode *DstPattern; // Resulting pattern.
411 unsigned AddedComplexity; // Add to matching pattern complexity.
413 ListInit *getPredicates() const { return Predicates; }
414 TreePatternNode *getSrcPattern() const { return SrcPattern; }
415 TreePatternNode *getDstPattern() const { return DstPattern; }
416 unsigned getAddedComplexity() const { return AddedComplexity; }
419 /// DAGISelEmitter - The top-level class which coordinates construction
420 /// and emission of the instruction selector.
422 class DAGISelEmitter : public TableGenBackend {
424 RecordKeeper &Records;
425 CodeGenTarget Target;
426 std::vector<CodeGenIntrinsic> Intrinsics;
428 std::map<Record*, SDNodeInfo> SDNodes;
429 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
430 std::map<Record*, ComplexPattern> ComplexPatterns;
431 std::map<Record*, TreePattern*> PatternFragments;
432 std::map<Record*, DAGInstruction> Instructions;
434 // Specific SDNode definitions:
435 Record *intrinsic_void_sdnode;
436 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
438 /// PatternsToMatch - All of the things we are matching on the DAG. The first
439 /// value is the pattern to match, the second pattern is the result to
441 std::vector<PatternToMatch> PatternsToMatch;
443 DAGISelEmitter(RecordKeeper &R) : Records(R) {}
445 // run - Output the isel, returning true on failure.
446 void run(std::ostream &OS);
448 const CodeGenTarget &getTargetInfo() const { return Target; }
450 Record *getSDNodeNamed(const std::string &Name) const;
452 const SDNodeInfo &getSDNodeInfo(Record *R) const {
453 assert(SDNodes.count(R) && "Unknown node!");
454 return SDNodes.find(R)->second;
457 const std::pair<Record*, std::string> &getSDNodeTransform(Record *R) const {
458 assert(SDNodeXForms.count(R) && "Invalid transform!");
459 return SDNodeXForms.find(R)->second;
462 const ComplexPattern &getComplexPattern(Record *R) const {
463 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
464 return ComplexPatterns.find(R)->second;
467 const CodeGenIntrinsic &getIntrinsic(Record *R) const {
468 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
469 if (Intrinsics[i].TheDef == R) return Intrinsics[i];
470 assert(0 && "Unknown intrinsic!");
474 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
475 assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
476 return Intrinsics[IID-1];
479 unsigned getIntrinsicID(Record *R) const {
480 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
481 if (Intrinsics[i].TheDef == R) return i;
482 assert(0 && "Unknown intrinsic!");
486 TreePattern *getPatternFragment(Record *R) const {
487 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
488 return PatternFragments.find(R)->second;
491 const DAGInstruction &getInstruction(Record *R) const {
492 assert(Instructions.count(R) && "Unknown instruction!");
493 return Instructions.find(R)->second;
496 Record *get_intrinsic_void_sdnode() const {
497 return intrinsic_void_sdnode;
499 Record *get_intrinsic_w_chain_sdnode() const {
500 return intrinsic_w_chain_sdnode;
502 Record *get_intrinsic_wo_chain_sdnode() const {
503 return intrinsic_wo_chain_sdnode;
508 void ParseNodeInfo();
509 void ParseNodeTransforms(std::ostream &OS);
510 void ParseComplexPatterns();
511 void ParsePatternFragments(std::ostream &OS);
512 void ParseInstructions();
513 void ParsePatterns();
514 void GenerateVariants();
515 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
516 std::map<std::string,
517 TreePatternNode*> &InstInputs,
518 std::map<std::string,
519 TreePatternNode*> &InstResults,
520 std::vector<Record*> &InstImpInputs,
521 std::vector<Record*> &InstImpResults);
522 void GenerateCodeForPattern(PatternToMatch &Pattern,
523 std::vector<std::pair<unsigned, std::string> > &GeneratedCode,
524 std::set<std::pair<unsigned, std::string> > &GeneratedDecl,
525 std::vector<std::string> &TargetOpcodes,
526 std::vector<std::string> &TargetVTs);
527 void EmitPatterns(std::vector<std::pair<PatternToMatch*,
528 std::vector<std::pair<unsigned, std::string> > > > &Patterns,
529 unsigned Indent, std::ostream &OS);
530 void EmitInstructionSelector(std::ostream &OS);
533 } // End llvm namespace