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