*** empty log message ***
[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/InstrForest.h"
20 #include "llvm/CodeGen/MachineCodeForInstruction.h"
21 #include "llvm/CodeGen/MachineCodeForBasicBlock.h"
22 #include "llvm/CodeGen/MachineCodeForMethod.h"
23 #include "llvm/Target/MachineRegInfo.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/BasicBlock.h"
26 #include "llvm/Function.h"
27 #include "llvm/iPHINode.h"
28 #include "Support/CommandLine.h"
29 using std::cerr;
30 using std::vector;
31
32 //******************** Internal Data Declarations ************************/
33
34
35 enum SelectDebugLevel_t {
36   Select_NoDebugInfo,
37   Select_PrintMachineCode, 
38   Select_DebugInstTrees, 
39   Select_DebugBurgTrees,
40 };
41
42
43 // Enable Debug Options to be specified on the command line
44 static cl::opt<SelectDebugLevel_t>
45 SelectDebugLevel("dselect", cl::Hidden,
46                  cl::desc("enable instruction selection debugging information"),
47                  cl::values(
48    clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
49    clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
50    clEnumValN(Select_DebugInstTrees,   "i",
51               "print debugging info for instruction selection"),
52    clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"),
53                             0));
54
55
56 //******************** Forward Function Declarations ***********************/
57
58
59 static bool SelectInstructionsForTree   (InstrTreeNode* treeRoot,
60                                          int goalnt,
61                                          TargetMachine &target);
62
63 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
64                                           int ruleForNode,
65                                           short* nts,
66                                           TargetMachine &target);
67
68 static void InsertCode4AllPhisInMeth(Function *F, TargetMachine &target);
69
70
71
72 //******************* Externally Visible Functions *************************/
73
74
75 //---------------------------------------------------------------------------
76 // Entry point for instruction selection using BURG.
77 // Returns true if instruction selection failed, false otherwise.
78 //---------------------------------------------------------------------------
79
80 bool
81 SelectInstructionsForMethod(Function *F, TargetMachine &target)
82 {
83   bool failed = false;
84   
85   //
86   // Build the instruction trees to be given as inputs to BURG.
87   // 
88   InstrForest instrForest(F);
89   
90   if (SelectDebugLevel >= Select_DebugInstTrees)
91     {
92       cerr << "\n\n*** Input to instruction selection for function "
93            << F->getName() << "\n\n";
94       F->dump();
95       
96       cerr << "\n\n*** Instruction trees for function "
97            << F->getName() << "\n\n";
98       instrForest.dump();
99     }
100   
101   //
102   // Invoke BURG instruction selection for each tree
103   // 
104   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
105        RI != instrForest.roots_end(); ++RI)
106     {
107       InstructionNode* basicNode = *RI;
108       assert(basicNode->parent() == NULL && "A `root' node has a parent?"); 
109       
110       // Invoke BURM to label each tree node with a state
111       burm_label(basicNode);
112       
113       if (SelectDebugLevel >= Select_DebugBurgTrees)
114         {
115           printcover(basicNode, 1, 0);
116           cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
117           printMatches(basicNode);
118         }
119       
120       // Then recursively walk the tree to select instructions
121       if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
122         {
123           failed = true;
124           break;
125         }
126     }
127   
128   //
129   // Record instructions in the vector for each basic block
130   // 
131   for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
132     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
133       MachineCodeForInstruction &mvec =MachineCodeForInstruction::get(II);
134       for (unsigned i=0; i < mvec.size(); i++)
135         MachineCodeForBasicBlock::get(BI).push_back(mvec[i]);
136     }
137
138   // Insert phi elimination code -- added by Ruchira
139   InsertCode4AllPhisInMeth(F, target);
140
141   
142   if (SelectDebugLevel >= Select_PrintMachineCode)
143     {
144       cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
145       MachineCodeForMethod::get(F).dump();
146     }
147   
148   return false;
149 }
150
151
152 //*********************** Private Functions *****************************/
153
154
155 //-------------------------------------------------------------------------
156 // Thid method inserts a copy instruction to a predecessor BB as a result
157 // of phi elimination.
158 //-------------------------------------------------------------------------
159
160 void
161 InsertPhiElimInstructions(BasicBlock *BB, const std::vector<MachineInstr*>& CpVec)
162
163   Instruction *TermInst = (Instruction*)BB->getTerminator();
164   MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
165   MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
166   
167   assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
168   
169   // get an iterator to machine instructions in the BB
170   MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
171   MachineCodeForBasicBlock::iterator MCIt =  bbMvec.begin();
172   
173   // find the position of first machine instruction generated by the
174   // terminator of this BB
175   for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
176     ;
177   assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
178   
179   // insert the copy instructions just before the first machine instruction
180   // generated for the terminator
181   bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
182   
183   //cerr << "\nPhiElimination copy inst: " <<   *CopyInstVec[0];
184 }
185
186
187 //-------------------------------------------------------------------------
188 // This method inserts phi elimination code for all BBs in a method
189 //-------------------------------------------------------------------------
190
191 void
192 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
193 {
194   // for all basic blocks in function
195   //
196   for (Function::iterator BB = F->begin(); BB != F->end(); ++BB) {
197     BasicBlock::InstListType &InstList = BB->getInstList();
198     for (BasicBlock::iterator IIt = InstList.begin();
199          PHINode *PN = dyn_cast<PHINode>(&*IIt); ++IIt) {
200       // FIXME: This is probably wrong...
201       Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
202         
203       // for each incoming value of the phi, insert phi elimination
204       //
205       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
206         // insert the copy instruction to the predecessor BB
207         vector<MachineInstr*> mvec, CpVec;
208         target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
209                                           mvec);
210         for (vector<MachineInstr*>::iterator MI=mvec.begin();
211              MI != mvec.end(); ++MI) {
212           vector<MachineInstr*> CpVec2 =
213             FixConstantOperandsForInstr(PN, *MI, target);
214           CpVec2.push_back(*MI);
215           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
216         }
217         
218         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
219       }
220       
221       vector<MachineInstr*> mvec;
222       target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
223       
224       // get an iterator to machine instructions in the BB
225       MachineCodeForBasicBlock& bbMvec = MachineCodeForBasicBlock::get(BB);
226       
227       bbMvec.insert(bbMvec.begin(), mvec.begin(), mvec.end());
228     }  // for each Phi Instr in BB
229   } // for all BBs in function
230 }
231
232
233 //---------------------------------------------------------------------------
234 // Function PostprocessMachineCodeForTree
235 // 
236 // Apply any final cleanups to machine code for the root of a subtree
237 // after selection for all its children has been completed.
238 //---------------------------------------------------------------------------
239
240 static void
241 PostprocessMachineCodeForTree(InstructionNode* instrNode,
242                               int ruleForNode,
243                               short* nts,
244                               TargetMachine &target)
245 {
246   // Fix up any constant operands in the machine instructions to either
247   // use an immediate field or to load the constant into a register
248   // Walk backwards and use direct indexes to allow insertion before current
249   // 
250   Instruction* vmInstr = instrNode->getInstruction();
251   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
252   for (int i = (int) mvec.size()-1; i >= 0; i--)
253     {
254       std::vector<MachineInstr*> loadConstVec =
255         FixConstantOperandsForInstr(vmInstr, mvec[i], target);
256       
257       if (loadConstVec.size() > 0)
258         mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
259     }
260 }
261
262 //---------------------------------------------------------------------------
263 // Function SelectInstructionsForTree 
264 // 
265 // Recursively walk the tree to select instructions.
266 // Do this top-down so that child instructions can exploit decisions
267 // made at the child instructions.
268 // 
269 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
270 // a branch-on-integer-register instruction, then the setle node
271 // can use that information to avoid generating the SUBcc instruction.
272 //
273 // Note that this cannot be done bottom-up because setle must do this
274 // only if it is a child of the branch (otherwise, the result of setle
275 // may be used by multiple instructions).
276 //---------------------------------------------------------------------------
277
278 bool
279 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
280                           TargetMachine &target)
281 {
282   // Get the rule that matches this node.
283   // 
284   int ruleForNode = burm_rule(treeRoot->state, goalnt);
285   
286   if (ruleForNode == 0)
287     {
288       cerr << "Could not match instruction tree for instr selection\n";
289       assert(0);
290       return true;
291     }
292   
293   // Get this rule's non-terminals and the corresponding child nodes (if any)
294   // 
295   short *nts = burm_nts[ruleForNode];
296   
297   // First, select instructions for the current node and rule.
298   // (If this is a list node, not an instruction, then skip this step).
299   // This function is specific to the target architecture.
300   // 
301   if (treeRoot->opLabel != VRegListOp)
302     {
303       std::vector<MachineInstr*> minstrVec;
304       
305       InstructionNode* instrNode = (InstructionNode*)treeRoot;
306       assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
307       
308       GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
309       
310       MachineCodeForInstruction &mvec = 
311         MachineCodeForInstruction::get(instrNode->getInstruction());
312       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
313     }
314   
315   // Then, recursively compile the child nodes, if any.
316   // 
317   if (nts[0])
318     { // i.e., there is at least one kid
319       InstrTreeNode* kids[2];
320       int currentRule = ruleForNode;
321       burm_kids(treeRoot, currentRule, kids);
322     
323       // First skip over any chain rules so that we don't visit
324       // the current node again.
325       // 
326       while (ThisIsAChainRule(currentRule))
327         {
328           currentRule = burm_rule(treeRoot->state, nts[0]);
329           nts = burm_nts[currentRule];
330           burm_kids(treeRoot, currentRule, kids);
331         }
332       
333       // Now we have the first non-chain rule so we have found
334       // the actual child nodes.  Recursively compile them.
335       // 
336       for (int i = 0; nts[i]; i++)
337         {
338           assert(i < 2);
339           InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
340           if (nodeType == InstrTreeNode::NTVRegListNode ||
341               nodeType == InstrTreeNode::NTInstructionNode)
342             {
343               if (SelectInstructionsForTree(kids[i], nts[i], target))
344                 return true;                    // failure
345             }
346         }
347     }
348   
349   // Finally, do any postprocessing on this node after its children
350   // have been translated
351   // 
352   if (treeRoot->opLabel != VRegListOp)
353     {
354       InstructionNode* instrNode = (InstructionNode*)treeRoot;
355       PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
356     }
357   
358   return false;                         // success
359 }
360