1. Add a bottom-up pass on BURG trees that is used to fix constant operands.
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelection.cpp
1 // $Id$ -*-c++-*-
2 //***************************************************************************
3 // File:
4 //      InstrSelection.cpp
5 // 
6 // Purpose:
7 //      Machine-independent driver file for instruction selection.
8 //      This file constructs a forest of BURG instruction trees and then
9 //      uses the BURG-generated tree grammar (BURM) to find the optimal
10 //      instruction sequences for a given machine.
11 //      
12 // History:
13 //      7/02/01  -  Vikram Adve  -  Created
14 //**************************************************************************/
15
16
17 #include "llvm/CodeGen/InstrSelection.h"
18 #include "llvm/CodeGen/InstrSelectionSupport.h"
19 #include "llvm/CodeGen/MachineInstr.h"
20 #include "llvm/Support/CommandLine.h"
21 #include "llvm/Instruction.h"
22 #include "llvm/BasicBlock.h"
23 #include "llvm/Method.h"
24
25 static bool SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
26                                       TargetMachine &target);
27
28
29 enum SelectDebugLevel_t {
30   Select_NoDebugInfo,
31   Select_PrintMachineCode, 
32   Select_DebugInstTrees, 
33   Select_DebugBurgTrees,
34 };
35
36 // Enable Debug Options to be specified on the command line
37 cl::Enum<enum SelectDebugLevel_t> SelectDebugLevel("dselect", cl::NoFlags,
38    "enable instruction selection debugging information",
39    clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
40    clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
41    clEnumValN(Select_DebugInstTrees,   "i", "print debugging info for instruction selection "),
42    clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"), 0);
43
44
45
46 //---------------------------------------------------------------------------
47 // Entry point for instruction selection using BURG.
48 // Returns true if instruction selection failed, false otherwise.
49 //---------------------------------------------------------------------------
50
51 bool
52 SelectInstructionsForMethod(Method* method, TargetMachine &target)
53 {
54   bool failed = false;
55   
56   //
57   // Build the instruction trees to be given as inputs to BURG.
58   // 
59   InstrForest instrForest(method);
60   
61   if (SelectDebugLevel >= Select_DebugInstTrees)
62     {
63       cout << "\n\n*** Instruction trees for method "
64            << (method->hasName()? method->getName() : "")
65            << endl << endl;
66       instrForest.dump();
67     }
68   
69   //
70   // Invoke BURG instruction selection for each tree
71   // 
72   const hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
73   for (hash_set<InstructionNode*>::const_iterator
74          treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
75        ++treeRootIter)
76     {
77       InstrTreeNode* basicNode = *treeRootIter;
78       
79       // Invoke BURM to label each tree node with a state
80       burm_label(basicNode);
81       
82       if (SelectDebugLevel >= Select_DebugBurgTrees)
83         {
84           printcover(basicNode, 1, 0);
85           cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
86           printMatches(basicNode);
87         }
88       
89       // Then recursively walk the tree to select instructions
90       if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
91         {
92           failed = true;
93           break;
94         }
95     }
96   
97   //
98   // Record instructions in the vector for each basic block
99   // 
100   for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
101     {
102       MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
103       for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
104         {
105           MachineCodeForVMInstr& mvec = (*II)->getMachineInstrVec();
106           for (unsigned i=0; i < mvec.size(); i++)
107             bbMvec.push_back(mvec[i]);
108         }
109     }
110   
111   if (SelectDebugLevel >= Select_PrintMachineCode)
112     {
113       cout << endl << "*** Machine instructions after INSTRUCTION SELECTION" << endl;
114       PrintMachineInstructions(method);
115     }
116   
117   return false;
118 }
119
120
121 //*********************** Private Functions *****************************/
122
123
124 //---------------------------------------------------------------------------
125 // Function PostprocessMachineCodeForTree
126 // 
127 // Apply any final cleanups to machine code for the root of a subtree
128 // after selection for all its children has been completed.
129 //---------------------------------------------------------------------------
130
131 void
132 PostprocessMachineCodeForTree(InstructionNode* instrNode,
133                               int ruleForNode,
134                               short* nts,
135                               TargetMachine &target)
136 {
137   // Fix up any constant operands in the machine instructions to either
138   // use an immediate field or to load the constant into a register
139   // Walk backwards and use direct indexes to allow insertion before current
140   // 
141   Instruction* vmInstr = instrNode->getInstruction();
142   MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
143   for (int i = (int) mvec.size()-1; i >= 0; i--)
144     {
145       vector<MachineInstr*> loadConstVec =
146         FixConstantOperandsForInstr(vmInstr, mvec[i], target);
147       
148       if (loadConstVec.size() > 0)
149         mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
150     }
151 }
152
153 //---------------------------------------------------------------------------
154 // Function SelectInstructionsForTree 
155 // 
156 // Recursively walk the tree to select instructions.
157 // Do this top-down so that child instructions can exploit decisions
158 // made at the child instructions.
159 // 
160 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
161 // a branch-on-integer-register instruction, then the setle node
162 // can use that information to avoid generating the SUBcc instruction.
163 //
164 // Note that this cannot be done bottom-up because setle must do this
165 // only if it is a child of the branch (otherwise, the result of setle
166 // may be used by multiple instructions).
167 //---------------------------------------------------------------------------
168
169 bool
170 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
171                           TargetMachine &target)
172 {
173   // Use a static vector to avoid allocating a new one per VM instruction
174   static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
175   
176   // Get the rule that matches this node.
177   // 
178   int ruleForNode = burm_rule(treeRoot->state, goalnt);
179   
180   if (ruleForNode == 0)
181     {
182       cerr << "Could not match instruction tree for instr selection" << endl;
183       assert(0);
184       return true;
185     }
186   
187   // Get this rule's non-terminals and the corresponding child nodes (if any)
188   // 
189   short *nts = burm_nts[ruleForNode];
190   
191   // First, select instructions for the current node and rule.
192   // (If this is a list node, not an instruction, then skip this step).
193   // This function is specific to the target architecture.
194   // 
195   if (treeRoot->opLabel != VRegListOp)
196     {
197       InstructionNode* instrNode = (InstructionNode*)treeRoot;
198       assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
199     
200       unsigned N = GetInstructionsByRule(instrNode, ruleForNode, nts, target,
201                                          minstrVec);
202       assert(N <= MAX_INSTR_PER_VMINSTR);
203       for (unsigned i=0; i < N; i++)
204         {
205           assert(minstrVec[i] != NULL);
206           instrNode->getInstruction()->addMachineInstruction(minstrVec[i]);
207         }
208     }
209   
210   // Then, recursively compile the child nodes, if any.
211   // 
212   if (nts[0])
213     { // i.e., there is at least one kid
214       InstrTreeNode* kids[2];
215       int currentRule = ruleForNode;
216       burm_kids(treeRoot, currentRule, kids);
217     
218       // First skip over any chain rules so that we don't visit
219       // the current node again.
220       // 
221       while (ThisIsAChainRule(currentRule))
222         {
223           currentRule = burm_rule(treeRoot->state, nts[0]);
224           nts = burm_nts[currentRule];
225           burm_kids(treeRoot, currentRule, kids);
226         }
227       
228       // Now we have the first non-chain rule so we have found
229       // the actual child nodes.  Recursively compile them.
230       // 
231       for (int i = 0; nts[i]; i++)
232         {
233           assert(i < 2);
234           InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
235           if (nodeType == InstrTreeNode::NTVRegListNode ||
236               nodeType == InstrTreeNode::NTInstructionNode)
237             {
238               if (SelectInstructionsForTree(kids[i], nts[i], target))
239                 return true;                    // failure
240             }
241         }
242     }
243   
244   // Finally, do any postprocessing on this node after its children
245   // have been translated
246   // 
247   if (treeRoot->opLabel != VRegListOp)
248     {
249       InstructionNode* instrNode = (InstructionNode*)treeRoot;
250       PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
251     }
252   
253   return false;                         // success
254 }
255