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