1 //===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
3 // This tablegen backend is responsible for emitting a description of the target
4 // instruction set for the code generator.
6 //===----------------------------------------------------------------------===//
8 #include "InstrSelectorEmitter.h"
9 #include "CodeGenWrappers.h"
11 #include "Support/Debug.h"
12 #include "Support/StringExtras.h"
15 NodeType::ArgResultTypes NodeType::Translate(Record *R) {
16 const std::string &Name = R->getName();
17 if (Name == "DNVT_any") return Any;
18 if (Name == "DNVT_void") return Void;
19 if (Name == "DNVT_val" ) return Val;
20 if (Name == "DNVT_arg0") return Arg0;
21 if (Name == "DNVT_arg1") return Arg1;
22 if (Name == "DNVT_ptr" ) return Ptr;
23 if (Name == "DNVT_i8" ) return I8;
24 throw "Unknown DagNodeValType '" + Name + "'!";
28 //===----------------------------------------------------------------------===//
29 // TreePatternNode implementation
32 /// getValueRecord - Returns the value of this tree node as a record. For now
33 /// we only allow DefInit's as our leaf values, so this is used.
34 Record *TreePatternNode::getValueRecord() const {
35 DefInit *DI = dynamic_cast<DefInit*>(getValue());
36 assert(DI && "Instruction Selector does not yet support non-def leaves!");
41 // updateNodeType - Set the node type of N to VT if VT contains information. If
42 // N already contains a conflicting type, then throw an exception
44 bool TreePatternNode::updateNodeType(MVT::ValueType VT,
45 const std::string &RecName) {
46 if (VT == MVT::Other || getType() == VT) return false;
47 if (getType() == MVT::Other) {
52 throw "Type inferfence contradiction found for pattern " + RecName;
55 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
56 /// are not themselves completely resolved, clone the nonterminal and resolve it
57 /// with the using context we provide.
59 void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
61 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
62 getChild(i)->InstantiateNonterminals(ISE);
66 // If this is a leaf, it might be a reference to a nonterminal! Check now.
67 Record *R = getValueRecord();
68 if (R->isSubClassOf("Nonterminal")) {
69 Pattern *NT = ISE.getPattern(R);
70 if (!NT->isResolved()) {
71 // We found an unresolved nonterminal reference. Ask the ISE to clone
72 // it for us, then update our reference to the fresh, new, resolved,
75 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
81 /// clone - Make a copy of this tree and all of its children.
83 TreePatternNode *TreePatternNode::clone() const {
86 New = new TreePatternNode(Value);
88 std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
89 CChildren.reserve(Children.size());
90 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
91 CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
92 New = new TreePatternNode(Operator, CChildren);
98 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
100 return OS << N.getType() << ":" << *N.getValue();
101 OS << "(" << N.getType() << ":";
102 OS << N.getOperator()->getName();
104 if (N.getNumChildren() != 0) {
105 OS << " " << *N.getChild(0);
106 for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
107 OS << ", " << *N.getChild(i);
112 void TreePatternNode::dump() const { std::cerr << *this; }
114 //===----------------------------------------------------------------------===//
115 // Pattern implementation
118 // Parse the specified DagInit into a TreePattern which we can use.
120 Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
121 InstrSelectorEmitter &ise)
122 : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
124 // First, parse the pattern...
125 Tree = ParseTreePattern(RawPat);
127 // Run the type-inference engine...
130 if (PTy == Instruction || PTy == Expander) {
131 // Check to make sure there is not any unset types in the tree pattern...
133 std::cerr << "In pattern: " << *Tree << "\n";
134 error("Could not infer all types!");
137 // Check to see if we have a top-level (set) of a register.
138 if (Tree->getOperator()->getName() == "set") {
139 assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
140 if (!Tree->getChild(0)->isLeaf())
141 error("Arg #0 of set should be a register or register class!");
142 ResultNode = Tree->getChild(0);
143 ResultName = Tree->getChildName(0);
144 Tree = Tree->getChild(1);
148 calculateArgs(Tree, "");
151 void Pattern::error(const std::string &Msg) const {
152 std::string M = "In ";
154 case Nonterminal: M += "nonterminal "; break;
155 case Instruction: M += "instruction "; break;
156 case Expander : M += "expander "; break;
158 throw M + TheRecord->getName() + ": " + Msg;
161 /// calculateArgs - Compute the list of all of the arguments to this pattern,
162 /// which are the non-void leaf nodes in this pattern.
164 void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
165 if (N->isLeaf() || N->getNumChildren() == 0) {
166 if (N->getType() != MVT::isVoid)
167 Args.push_back(std::make_pair(N, Name));
169 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
170 calculateArgs(N->getChild(i), N->getChildName(i));
174 /// getIntrinsicType - Check to see if the specified record has an intrinsic
175 /// type which should be applied to it. This infer the type of register
176 /// references from the register file information, for example.
178 MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
179 // Check to see if this is a register or a register class...
180 if (R->isSubClassOf("RegisterClass"))
181 return getValueType(R->getValueAsDef("RegType"));
182 else if (R->isSubClassOf("Nonterminal"))
183 return ISE.ReadNonterminal(R)->getTree()->getType();
184 else if (R->isSubClassOf("Register")) {
185 std::cerr << "WARNING: Explicit registers not handled yet!\n";
189 error("Unknown value used: " + R->getName());
193 TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
194 Record *Operator = Dag->getNodeType();
196 if (Operator->isSubClassOf("ValueType")) {
197 // If the operator is a ValueType, then this must be "type cast" of a leaf
199 if (Dag->getNumArgs() != 1)
200 error("Type cast only valid for a leaf node!");
202 Init *Arg = Dag->getArg(0);
203 TreePatternNode *New;
204 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
205 New = new TreePatternNode(DI);
206 // If it's a regclass or something else known, set the type.
207 New->setType(getIntrinsicType(DI->getDef()));
208 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
209 New = ParseTreePattern(DI);
212 error("Unknown leaf value for tree pattern!");
215 // Apply the type cast...
216 New->updateNodeType(getValueType(Operator), TheRecord->getName());
220 if (!ISE.getNodeTypes().count(Operator))
221 error("Unrecognized node '" + Operator->getName() + "'!");
223 std::vector<std::pair<TreePatternNode*, std::string> > Children;
225 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
226 Init *Arg = Dag->getArg(i);
227 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
228 Children.push_back(std::make_pair(ParseTreePattern(DI),
229 Dag->getArgName(i)));
230 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
231 Record *R = DefI->getDef();
232 // Direct reference to a leaf DagNode? Turn it into a DagNode if its own.
233 if (R->isSubClassOf("DagNode")) {
234 Dag->setArg(i, new DagInit(R,
235 std::vector<std::pair<Init*, std::string> >()));
236 --i; // Revisit this node...
238 Children.push_back(std::make_pair(new TreePatternNode(DefI),
239 Dag->getArgName(i)));
240 // If it's a regclass or something else known, set the type.
241 Children.back().first->setType(getIntrinsicType(R));
245 error("Unknown leaf value for tree pattern!");
249 return new TreePatternNode(Operator, Children);
252 void Pattern::InferAllTypes() {
253 bool MadeChange, AnyUnset;
256 AnyUnset = InferTypes(Tree, MadeChange);
257 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
258 Resolved = !AnyUnset;
262 // InferTypes - Perform type inference on the tree, returning true if there
263 // are any remaining untyped nodes and setting MadeChange if any changes were
265 bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
266 if (N->isLeaf()) return N->getType() == MVT::Other;
268 bool AnyUnset = false;
269 Record *Operator = N->getOperator();
270 const NodeType &NT = ISE.getNodeType(Operator);
272 // Check to see if we can infer anything about the argument types from the
274 if (N->getNumChildren() != NT.ArgTypes.size())
275 error("Incorrect number of children for " + Operator->getName() + " node!");
277 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
278 TreePatternNode *Child = N->getChild(i);
279 AnyUnset |= InferTypes(Child, MadeChange);
281 switch (NT.ArgTypes[i]) {
282 case NodeType::Any: break;
284 MadeChange |= Child->updateNodeType(MVT::i1, TheRecord->getName());
287 MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
288 TheRecord->getName());
291 MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
292 TheRecord->getName());
295 if (Child->getType() == MVT::isVoid)
296 error("Inferred a void node in an illegal place!");
299 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
300 TheRecord->getName());
303 MadeChange |= Child->updateNodeType(MVT::isVoid, TheRecord->getName());
305 default: assert(0 && "Invalid argument ArgType!");
309 // See if we can infer anything about the return type now...
310 switch (NT.ResultType) {
311 case NodeType::Any: break;
313 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
316 MadeChange |= N->updateNodeType(MVT::i1, TheRecord->getName());
319 MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
320 TheRecord->getName());
323 MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
324 TheRecord->getName());
327 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
328 TheRecord->getName());
331 if (N->getType() == MVT::isVoid)
332 error("Inferred a void node in an illegal place!");
335 assert(0 && "Unhandled type constraint!");
339 return AnyUnset | N->getType() == MVT::Other;
342 /// clone - This method is used to make an exact copy of the current pattern,
343 /// then change the "TheRecord" instance variable to the specified record.
345 Pattern *Pattern::clone(Record *R) const {
346 assert(PTy == Nonterminal && "Can only clone nonterminals");
347 return new Pattern(Tree->clone(), R, Resolved, ISE);
352 std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
353 switch (P.getPatternType()) {
354 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
355 case Pattern::Instruction: OS << "Instruction pattern "; break;
356 case Pattern::Expander: OS << "Expander pattern "; break;
359 OS << P.getRecord()->getName() << ":\t";
361 if (Record *Result = P.getResult())
362 OS << Result->getName() << " = ";
366 OS << " [not completely resolved]";
370 void Pattern::dump() const { std::cerr << *this; }
374 /// getSlotName - If this is a leaf node, return the slot name that the operand
376 std::string Pattern::getSlotName() const {
377 if (getPatternType() == Pattern::Nonterminal) {
378 // Just use the nonterminal name, which will already include the type if
379 // it has been cloned.
380 return getRecord()->getName();
382 std::string SlotName;
384 SlotName = getResult()->getName()+"_";
387 return SlotName + getName(getTree()->getType());
391 /// getSlotName - If this is a leaf node, return the slot name that the
392 /// operand will update.
393 std::string Pattern::getSlotName(Record *R) {
394 if (R->isSubClassOf("Nonterminal")) {
395 // Just use the nonterminal name, which will already include the type if
396 // it has been cloned.
398 } else if (R->isSubClassOf("RegisterClass")) {
399 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
400 return R->getName() + "_" + getName(Ty);
402 assert(0 && "Don't know how to get a slot name for this!");
406 //===----------------------------------------------------------------------===//
407 // PatternOrganizer implementation
410 /// addPattern - Add the specified pattern to the appropriate location in the
412 void PatternOrganizer::addPattern(Pattern *P) {
413 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
414 if (!P->getTree()->isLeaf())
415 Nodes[P->getTree()->getOperator()].push_back(P);
417 // Right now we only support DefInit's with node types...
418 Nodes[P->getTree()->getValueRecord()].push_back(P);
424 //===----------------------------------------------------------------------===//
425 // InstrSelectorEmitter implementation
428 /// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
429 /// turning them into the more accessible NodeTypes data structure.
431 void InstrSelectorEmitter::ReadNodeTypes() {
432 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
433 DEBUG(std::cerr << "Getting node types: ");
434 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
435 Record *Node = Nodes[i];
437 // Translate the return type...
438 NodeType::ArgResultTypes RetTy =
439 NodeType::Translate(Node->getValueAsDef("RetType"));
441 // Translate the arguments...
442 ListInit *Args = Node->getValueAsListInit("ArgTypes");
443 std::vector<NodeType::ArgResultTypes> ArgTypes;
445 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
446 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
447 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
449 throw "In node " + Node->getName() + ", argument is not a Def!";
451 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
452 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
453 if (a == 1 && ArgTypes.back() == NodeType::Arg1)
454 throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
456 if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
457 (RetTy == NodeType::Arg1 && Args->getSize() < 2))
458 throw "In node " + Node->getName() +
459 ", invalid return type for node with this many operands!";
461 // Add the node type mapping now...
462 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
463 DEBUG(std::cerr << Node->getName() << ", ");
465 DEBUG(std::cerr << "DONE!\n");
468 Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
469 Pattern *&P = Patterns[R];
470 if (P) return P; // Don't reread it!
472 DagInit *DI = R->getValueAsDag("Pattern");
473 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
474 DEBUG(std::cerr << "Parsed " << *P << "\n");
479 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
481 void InstrSelectorEmitter::ReadNonterminals() {
482 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
483 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
484 ReadNonterminal(NTs[i]);
488 /// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
489 /// those with a useful Pattern field.
491 void InstrSelectorEmitter::ReadInstructionPatterns() {
492 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
493 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
494 Record *Inst = Insts[i];
495 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
496 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
497 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
502 /// ReadExpanderPatterns - Read in all expander patterns...
504 void InstrSelectorEmitter::ReadExpanderPatterns() {
505 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
506 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
507 Record *Expander = Expanders[i];
508 DagInit *DI = Expander->getValueAsDag("Pattern");
509 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
510 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
515 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
516 // information from the context that they are used in.
518 void InstrSelectorEmitter::InstantiateNonterminals() {
519 DEBUG(std::cerr << "Instantiating nonterminals:\n");
520 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
521 E = Patterns.end(); I != E; ++I)
522 if (I->second->isResolved())
523 I->second->InstantiateNonterminals();
526 /// InstantiateNonterminal - This method takes the nonterminal specified by
527 /// NT, which should not be completely resolved, clones it, applies ResultTy
528 /// to its root, then runs the type inference stuff on it. This should
529 /// produce a newly resolved nonterminal, which we make a record for and
530 /// return. To be extra fancy and efficient, this only makes one clone for
531 /// each type it is instantiated with.
532 Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
533 MVT::ValueType ResultTy) {
534 assert(!NT->isResolved() && "Nonterminal is already resolved!");
536 // Check to see if we have already instantiated this pair...
537 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
538 if (Slot) return Slot;
540 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
542 // Copy over the superclasses...
543 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
544 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
545 New->addSuperClass(SCs[i]);
547 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
548 << "' for type '" << getName(ResultTy) << "', producing '"
549 << New->getName() << "'\n");
551 // Copy the pattern...
552 Pattern *NewPat = NT->clone(New);
554 // Apply the type to the root...
555 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
558 NewPat->InferAllTypes();
560 // Make sure everything is good to go now...
561 if (!NewPat->isResolved())
562 NewPat->error("Instantiating nonterminal did not resolve all types!");
564 // Add the pattern to the patterns map, add the record to the RecordKeeper,
565 // return the new record.
566 Patterns[New] = NewPat;
571 // CalculateComputableValues - Fill in the ComputableValues map through
572 // analysis of the patterns we are playing with.
573 void InstrSelectorEmitter::CalculateComputableValues() {
574 // Loop over all of the patterns, adding them to the ComputableValues map
575 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
576 E = Patterns.end(); I != E; ++I)
577 if (I->second->isResolved()) {
578 // We don't want to add patterns like R32 = R32. This is a hack working
579 // around a special case of a general problem, but for now we explicitly
580 // forbid these patterns. They can never match anyway.
581 Pattern *P = I->second;
582 if (!P->getResult() || !P->getTree()->isLeaf() ||
583 P->getResult() != P->getTree()->getValueRecord())
584 ComputableValues.addPattern(P);
589 // MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
590 // patterns which have the same top-level structure as P from the 'From' list to
592 static void MoveIdenticalPatterns(TreePatternNode *P,
593 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
594 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
595 assert(!P->isLeaf() && "All leaves are identical!");
597 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
598 for (unsigned i = 0; i != From.size(); ++i) {
599 TreePatternNode *N = From[i].second;
600 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
601 assert(PChildren.size() == N->getChildren().size() &&
602 "Nodes with different arity??");
603 bool isDifferent = false;
604 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
605 TreePatternNode *PC = PChildren[c];
606 TreePatternNode *NC = N->getChild(c);
607 if (PC->isLeaf() != NC->isLeaf()) {
613 if (PC->getOperator() != NC->getOperator()) {
617 } else { // It's a leaf!
618 if (PC->getValueRecord() != NC->getValueRecord()) {
624 // If it's the same as the reference one, move it over now...
626 To.push_back(std::make_pair(From[i].first, N));
627 From.erase(From.begin()+i);
628 --i; // Don't skip an entry...
634 static std::string getNodeName(Record *R) {
635 RecordVal *RV = R->getValue("EnumName");
637 if (Init *I = RV->getValue())
638 if (StringInit *SI = dynamic_cast<StringInit*>(I))
639 return SI->getValue();
644 static void EmitPatternPredicates(TreePatternNode *Tree,
645 const std::string &VarName, std::ostream &OS){
646 OS << " && " << VarName << "->getNodeType() == ISD::"
647 << getNodeName(Tree->getOperator());
649 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
650 if (!Tree->getChild(c)->isLeaf())
651 EmitPatternPredicates(Tree->getChild(c),
652 VarName + "->getUse(" + utostr(c)+")", OS);
655 static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
657 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
658 if (Tree->getChild(c)->isLeaf()) {
660 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
661 << VarName << "->getUse(" << c << "))";
663 EmitPatternCosts(Tree->getChild(c),
664 VarName + "->getUse(" + utostr(c) + ")", OS);
669 // EmitMatchCosters - Given a list of patterns, which all have the same root
670 // pattern operator, emit an efficient decision tree to decide which one to
671 // pick. This is structured this way to avoid reevaluations of non-obvious
673 void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
674 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
675 const std::string &VarPrefix,
676 unsigned IndentAmt) {
677 assert(!Patterns.empty() && "No patterns to emit matchers for!");
678 std::string Indent(IndentAmt, ' ');
680 // Load all of the operands of the root node into scalars for fast access
681 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
682 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
683 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
684 << " = N->getUse(" << i << ");\n";
686 // Compute the costs of computing the various nonterminals/registers, which
687 // are directly used at this level.
688 OS << "\n" << Indent << "// Operand matching costs...\n";
689 std::set<std::string> ComputedValues; // Avoid duplicate computations...
690 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
691 TreePatternNode *NParent = Patterns[i].second;
692 for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
693 TreePatternNode *N = NParent->getChild(c);
695 Record *VR = N->getValueRecord();
696 const std::string &LeafName = VR->getName();
697 std::string OpName = VarPrefix + "_Op" + utostr(c);
698 std::string ValName = OpName + "_" + LeafName + "_Cost";
699 if (!ComputedValues.count(ValName)) {
700 OS << Indent << "unsigned " << ValName << " = Match_"
701 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
702 ComputedValues.insert(ValName);
710 std::string LocCostName = VarPrefix + "_Cost";
711 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
712 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
715 // Separate out all of the patterns into groups based on what their top-level
716 // signature looks like...
717 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
718 while (!PatternsLeft.empty()) {
719 // Process all of the patterns that have the same signature as the last
721 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
722 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
723 assert(!Group.empty() && "Didn't at least pick the source pattern?");
726 OS << "PROCESSING GROUP:\n";
727 for (unsigned i = 0, e = Group.size(); i != e; ++i)
728 OS << " " << *Group[i].first << "\n";
732 OS << Indent << "{ // ";
734 if (Group.size() != 1) {
735 OS << Group.size() << " size group...\n";
736 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
738 OS << *Group[0].first << "\n";
739 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
740 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
743 OS << Indent << " unsigned " << LocCostName << " = ";
744 if (Group.size() == 1)
745 OS << "1;\n"; // Add inst cost if at individual rec
749 // Loop over all of the operands, adding in their costs...
750 TreePatternNode *N = Group[0].second;
751 const std::vector<TreePatternNode*> &Children = N->getChildren();
753 // If necessary, emit conditionals to check for the appropriate tree
755 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
756 TreePatternNode *C = Children[i];
758 // We already calculated the cost for this leaf, add it in now...
759 OS << Indent << " " << LocCostName << " += "
760 << VarPrefix << "_Op" << utostr(i) << "_"
761 << C->getValueRecord()->getName() << "_Cost;\n";
763 // If it's not a leaf, we have to check to make sure that the current
764 // node has the appropriate structure, then recurse into it...
765 OS << Indent << " if (" << VarPrefix << "_Op" << i
766 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
768 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
769 for (unsigned n = 0, e = Group.size(); n != e; ++n)
770 SubPatterns.push_back(std::make_pair(Group[n].first,
771 Group[n].second->getChild(i)));
772 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
774 OS << Indent << " }\n";
778 // If the cost for this match is less than the minimum computed cost so far,
779 // update the minimum cost and selected pattern.
780 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
781 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
782 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
784 OS << Indent << "}\n";
788 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
789 Pattern *P = Patterns[i].first;
790 TreePatternNode *PTree = P->getTree();
791 unsigned PatternCost = 1;
793 // Check to see if there are any non-leaf elements in the pattern. If so,
794 // we need to emit a predicate for this match.
795 bool AnyNonLeaf = false;
796 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
797 if (!PTree->getChild(c)->isLeaf()) {
802 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
803 OS << " {// " << *P << "\n";
805 // We need to emit a predicate to make sure the tree pattern matches, do
808 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
809 if (!PTree->getChild(c)->isLeaf())
810 EmitPatternPredicates(PTree->getChild(c),
811 VarPrefix + "_Op" + utostr(c), OS);
813 OS << ") {\n // " << *P << "\n";
816 OS << " unsigned PatCost = " << PatternCost;
818 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
819 if (PTree->getChild(c)->isLeaf()) {
820 OS << " + " << VarPrefix << "_Op" << c << "_"
821 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
823 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
826 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
827 << P->getRecord()->getName() << "_Pattern; }\n"
832 static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
833 std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
836 // If this is a leaf, register or nonterminal reference...
837 std::string SlotName = Pattern::getSlotName(N->getValueRecord());
838 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
839 << SlotName << "(" << Name << ", MBB);\n";
840 Operands.push_back(std::make_pair(N, Name+"Val"));
841 } else if (N->getNumChildren() == 0) {
842 // This is a reference to a leaf tree node, like an immediate or frame
844 if (N->getType() != MVT::isVoid) {
845 std::string SlotName =
846 getNodeName(N->getOperator()) + "_" + getName(N->getType());
847 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = "
848 << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
849 << SlotName << "_Slot);\n";
850 Operands.push_back(std::make_pair(N, Name+"Val"));
853 // Otherwise this is an interior node...
854 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
855 std::string ChildName = Name + "_Op" + utostr(i);
856 OS << " SelectionDAGNode *" << ChildName << " = " << Name
857 << "->getUse(" << i << ");\n";
858 ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
863 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
864 /// process for the expander pattern P. This argument may be referencing some
865 /// values defined in P, or may just be physical register references or
866 /// something like that. If PrintArg is true, we are printing out arguments to
867 /// the BuildMI call. If it is false, we are printing the result register
869 void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
870 const std::string &NameVar,
871 TreePatternNode *ArgDeclNode,
872 Pattern *P, bool PrintArg,
874 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
875 Record *Arg = DI->getDef();
876 if (!ArgDeclNode->isLeaf() && ArgDeclNode->getNumChildren() != 0)
877 P->error("Expected leaf node as argument!");
878 Record *ArgDecl = ArgDeclNode->isLeaf() ? ArgDeclNode->getValueRecord() :
879 ArgDeclNode->getOperator();
880 if (Arg->isSubClassOf("Register")) {
881 // This is a physical register reference... make sure that the instruction
882 // requested a register!
883 if (!ArgDecl->isSubClassOf("RegisterClass"))
884 P->error("Argument mismatch for instruction pattern!");
886 // FIXME: This should check to see if the register is in the specified
888 if (PrintArg) OS << ".addReg(";
889 OS << getQualifiedName(Arg);
890 if (PrintArg) OS << ")";
892 } else if (Arg->isSubClassOf("RegisterClass")) {
893 // If this is a symbolic register class reference, we must be using a
895 if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
896 if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
898 if (PrintArg) OS << ".addReg(";
900 if (PrintArg) OS << ")";
902 } else if (Arg->getName() == "frameidx") {
903 if (!PrintArg) P->error("Cannot define a new frameidx value!");
904 OS << ".addFrameIndex(" << NameVar << ")";
906 } else if (Arg->getName() == "basicblock") {
907 if (!PrintArg) P->error("Cannot define a new basicblock value!");
908 OS << ".addMBB(" << NameVar << ")";
911 P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
912 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
913 if (!NameVar.empty())
914 P->error("Illegal to specify a name for a constant initializer arg!");
916 // Hack this check to allow R32 values with 0 as the initializer for memory
917 // references... FIXME!
918 if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
919 ArgDeclNode->getValueRecord()->getName() == "R32") {
922 if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
923 P->error("Illegal immediate int value '" + itostr(II->getValue()) +
925 OS << ".addZImm(" << II->getValue() << ")";
929 P->error("Unknown operand type to expander!");
932 static std::string getArgName(Pattern *P, const std::string &ArgName,
933 const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
934 assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
935 if (ArgName.empty()) return "";
937 for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
938 if (P->getArgName(i) == ArgName)
939 return Operands[i].second + "->Val";
941 if (ArgName == P->getResultName())
943 P->error("Pattern does not define a value named $" + ArgName + "!");
948 void InstrSelectorEmitter::run(std::ostream &OS) {
949 // Type-check all of the node types to ensure we "understand" them.
952 // Read in all of the nonterminals, instructions, and expanders...
954 ReadInstructionPatterns();
955 ReadExpanderPatterns();
957 // Instantiate any unresolved nonterminals with information from the context
958 // that they are used in.
959 InstantiateNonterminals();
961 // Clear InstantiatedNTs, we don't need it anymore...
962 InstantiatedNTs.clear();
964 DEBUG(std::cerr << "Patterns acquired:\n");
965 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
966 E = Patterns.end(); I != E; ++I)
967 if (I->second->isResolved())
968 DEBUG(std::cerr << " " << *I->second << "\n");
970 CalculateComputableValues();
972 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
974 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
976 // Output the slot number enums...
977 OS << "\nenum { // Slot numbers...\n"
978 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
979 for (PatternOrganizer::iterator I = ComputableValues.begin(),
980 E = ComputableValues.end(); I != E; ++I)
981 OS << " " << I->first << "_Slot,\n";
982 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
984 // Output the reduction value typedefs...
985 for (PatternOrganizer::iterator I = ComputableValues.begin(),
986 E = ComputableValues.end(); I != E; ++I) {
988 OS << "typedef ReducedValue<unsigned, " << I->first
989 << "_Slot> ReducedValue_" << I->first << ";\n";
992 // Output the pattern enums...
994 << "enum { // Patterns...\n"
995 << " NotComputed = 0,\n"
996 << " NoMatchPattern, \n";
997 for (PatternOrganizer::iterator I = ComputableValues.begin(),
998 E = ComputableValues.end(); I != E; ++I) {
999 OS << " // " << I->first << " patterns...\n";
1000 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1001 E = I->second.end(); J != E; ++J)
1002 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1003 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
1007 //===--------------------------------------------------------------------===//
1008 // Emit the class definition...
1010 OS << "namespace {\n"
1011 << " class " << Target.getName() << "ISel {\n"
1012 << " SelectionDAG &DAG;\n"
1014 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1015 << " void generateCode();\n"
1017 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1018 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
1019 "ualRegister(RC);\n"
1021 << " // DAG matching methods for classes... all of these methods"
1022 " return the cost\n"
1023 << " // of producing a value of the specified class and type, which"
1025 << " // added to the DAG node.\n";
1027 // Output all of the matching prototypes for slots...
1028 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1029 E = ComputableValues.end(); I != E; ++I)
1030 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1031 OS << "\n // DAG matching methods for DAG nodes...\n";
1033 // Output all of the matching prototypes for slot/node pairs
1034 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1035 E = ComputableValues.end(); I != E; ++I)
1036 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1037 E = I->second.end(); J != E; ++J)
1038 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
1039 << "(SelectionDAGNode *N);\n";
1041 // Output all of the dag reduction methods prototypes...
1042 OS << "\n // DAG reduction methods...\n";
1043 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1044 E = ComputableValues.end(); I != E; ++I)
1045 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
1046 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1047 << "MachineBasicBlock *MBB);\n";
1050 // Emit the generateCode entry-point...
1051 OS << "void X86ISel::generateCode() {\n"
1052 << " SelectionDAGNode *Root = DAG.getRoot();\n"
1053 << " assert(Root->getValueType() == MVT::isVoid && "
1054 "\"Root of DAG produces value??\");\n\n"
1055 << " std::cerr << \"\\n\";\n"
1056 << " unsigned Cost = Match_Void_void(Root);\n"
1057 << " if (Cost >= ~0U >> 1) {\n"
1058 << " std::cerr << \"Match failed!\\n\";\n"
1059 << " Root->dump();\n"
1062 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1063 << " Reduce_Void_void(Root, 0);\n"
1065 << "//===" << std::string(70, '-') << "===//\n"
1066 << "// Matching methods...\n"
1069 //===--------------------------------------------------------------------===//
1070 // Emit all of the matcher methods...
1072 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1073 E = ComputableValues.end(); I != E; ++I) {
1074 const std::string &SlotName = I->first;
1075 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1076 << "(SelectionDAGNode *N) {\n"
1077 << " assert(N->getValueType() == MVT::"
1078 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1079 << ");\n" << " // If we already have a cost available for " << SlotName
1081 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1082 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1083 << " unsigned Cost;\n"
1084 << " switch (N->getNodeType()) {\n"
1085 << " default: Cost = ~0U >> 1; // Match failed\n"
1086 << " N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1089 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1090 E = I->second.end(); J != E; ++J)
1091 if (!J->first->isSubClassOf("Nonterminal"))
1092 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1093 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1094 OS << " }\n"; // End of the switch statement
1096 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1097 // match multiple root nodes, so they cannot be handled with the switch...
1098 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1099 E = I->second.end(); J != E; ++J)
1100 if (J->first->isSubClassOf("Nonterminal")) {
1101 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1102 << getNodeName(J->first) << "(N);\n"
1103 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1104 << getNodeName(J->first) << "_Cost;\n";
1107 OS << " return Cost;\n}\n\n";
1109 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1110 E = I->second.end(); J != E; ++J) {
1111 Record *Operator = J->first;
1112 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1114 OS << "unsigned " << Target.getName() << "ISel::Match_";
1115 if (!isNonterm) OS << SlotName << "_";
1116 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1117 << " unsigned Pattern = NoMatchPattern;\n"
1118 << " unsigned MinCost = ~0U >> 1;\n";
1120 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1121 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1122 Patterns.push_back(std::make_pair(J->second[i],
1123 J->second[i]->getTree()));
1124 EmitMatchCosters(OS, Patterns, "N", 2);
1126 OS << "\n N->setPatternCostFor(" << SlotName
1127 << "_Slot, Pattern, MinCost, NumSlots);\n"
1128 << " return MinCost;\n"
1134 //===--------------------------------------------------------------------===//
1135 // Emit all of the reducer methods...
1137 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1138 << "// Reducer methods...\n"
1141 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1142 E = ComputableValues.end(); I != E; ++I) {
1143 const std::string &SlotName = I->first;
1144 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1145 << "ISel::Reduce_" << SlotName
1146 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1147 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1148 << SlotName << ">(" << SlotName << "_Slot);\n"
1149 << " if (Val) return Val;\n"
1150 << " if (N->getBB()) MBB = N->getBB();\n\n"
1151 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1153 // Loop over all of the patterns that can produce a value for this slot...
1154 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1155 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1156 E = NodesForSlot.end(); J != E; ++J)
1157 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1158 Pattern *P = J->second[i];
1159 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1160 << " // " << *P << "\n";
1161 // Loop over the operands, reducing them...
1162 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1163 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1165 // Now that we have reduced all of our operands, and have the values
1166 // that reduction produces, perform the reduction action for this
1170 // If the pattern produces a register result, generate a new register
1172 if (Record *R = P->getResult()) {
1173 assert(R->isSubClassOf("RegisterClass") &&
1174 "Only handle register class results so far!");
1175 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1176 << "::" << R->getName() << "RegisterClass);\n";
1178 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1180 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1184 // Print out the pattern that matched...
1185 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1186 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1187 if (Operands[i].first->isLeaf()) {
1188 Record *RV = Operands[i].first->getValueRecord();
1189 assert(RV->isSubClassOf("RegisterClass") &&
1190 "Only handles registers here so far!");
1191 OS << " << \" %reg\" << " << Operands[i].second
1194 OS << " << ' ' << " << Operands[i].second
1197 DEBUG(OS << " << \"\\n\";\n");
1199 // Generate the reduction code appropriate to the particular type of
1200 // pattern that this is...
1201 switch (P->getPatternType()) {
1202 case Pattern::Instruction:
1203 // Instruction patterns just emit a single MachineInstr, using BuildMI
1204 OS << " BuildMI(MBB, " << Target.getName() << "::"
1205 << P->getRecord()->getName() << ", " << Operands.size();
1206 if (P->getResult()) OS << ", NewReg";
1209 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1210 TreePatternNode *Op = Operands[i].first;
1212 Record *RV = Op->getValueRecord();
1213 assert(RV->isSubClassOf("RegisterClass") &&
1214 "Only handles registers here so far!");
1215 OS << ".addReg(" << Operands[i].second << "->Val)";
1216 } else if (Op->getOperator()->getName() == "imm") {
1217 OS << ".addZImm(" << Operands[i].second << "->Val)";
1218 } else if (Op->getOperator()->getName() == "basicblock") {
1219 OS << ".addMBB(" << Operands[i].second << "->Val)";
1221 assert(0 && "Unknown value type!");
1226 case Pattern::Expander: {
1227 // Expander patterns emit one machine instr for each instruction in
1228 // the list of instructions expanded to.
1229 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1230 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1231 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1232 if (!DIInst) P->error("Result list must contain instructions!");
1233 Record *InstRec = DIInst->getNodeType();
1234 Pattern *InstPat = getPattern(InstRec);
1235 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1236 P->error("Instruction list must contain Instruction patterns!");
1238 bool hasResult = InstPat->getResult() != 0;
1239 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1240 P->error("Incorrect number of arguments specified for inst '" +
1241 InstPat->getRecord()->getName() + "' in result list!");
1244 // Start emission of the instruction...
1245 OS << " BuildMI(MBB, " << Target.getName() << "::"
1246 << InstRec->getName() << ", "
1247 << DIInst->getNumArgs()-hasResult;
1248 // Emit register result if necessary..
1250 std::string ArgNameVal =
1251 getArgName(P, DIInst->getArgName(0), Operands);
1252 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1253 InstPat->getResultNode(), P, false,
1258 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1259 std::string ArgNameVal =
1260 getArgName(P, DIInst->getArgName(i), Operands);
1262 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1263 InstPat->getArg(i-hasResult), P, true, OS);
1271 assert(0 && "Reduction of this type of pattern not implemented!");
1274 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1280 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1281 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1282 << " return Val;\n}\n\n";