Remove unneccesary &*
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrSelection.cpp
1 //===- InstrSelection.cpp - Machine Independant Inst Selection Driver -----===//
2 //
3 // Machine-independent driver file for instruction selection.  This file
4 // constructs a forest of BURG instruction trees and then uses the
5 // BURG-generated tree grammar (BURM) to find the optimal instruction sequences
6 // for a given machine.
7 //      
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/CodeGen/InstrSelection.h"
11 #include "llvm/CodeGen/InstrSelectionSupport.h"
12 #include "llvm/CodeGen/InstrForest.h"
13 #include "llvm/CodeGen/MachineCodeForInstruction.h"
14 #include "llvm/CodeGen/MachineFunction.h"
15 #include "llvm/Target/TargetRegInfo.h"
16 #include "llvm/Target/TargetMachine.h"
17 #include "llvm/Function.h"
18 #include "llvm/iPHINode.h"
19 #include "llvm/Pass.h"
20 #include "Support/CommandLine.h"
21 #include "Support/LeakDetector.h"
22 using std::vector;
23
24 std::vector<MachineInstr*>
25 FixConstantOperandsForInstr(Instruction* vmInstr, MachineInstr* minstr,
26                             TargetMachine& target);
27
28 namespace {
29   //===--------------------------------------------------------------------===//
30   // SelectDebugLevel - Allow command line control over debugging.
31   //
32   enum SelectDebugLevel_t {
33     Select_NoDebugInfo,
34     Select_PrintMachineCode, 
35     Select_DebugInstTrees, 
36     Select_DebugBurgTrees,
37   };
38   
39   // Enable Debug Options to be specified on the command line
40   cl::opt<SelectDebugLevel_t>
41   SelectDebugLevel("dselect", cl::Hidden,
42                    cl::desc("enable instruction selection debug information"),
43                    cl::values(
44      clEnumValN(Select_NoDebugInfo,      "n", "disable debug output"),
45      clEnumValN(Select_PrintMachineCode, "y", "print generated machine code"),
46      clEnumValN(Select_DebugInstTrees,   "i",
47                 "print debugging info for instruction selection"),
48      clEnumValN(Select_DebugBurgTrees,   "b", "print burg trees"),
49                               0));
50
51
52   //===--------------------------------------------------------------------===//
53   //  InstructionSelection Pass
54   //
55   // This is the actual pass object that drives the instruction selection
56   // process.
57   //
58   class InstructionSelection : public FunctionPass {
59     TargetMachine &Target;
60     void InsertCodeForPhis(Function &F);
61     void InsertPhiElimInstructions(BasicBlock *BB,
62                                    const vector<MachineInstr*>& CpVec);
63     void SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt);
64     void PostprocessMachineCodeForTree(InstructionNode* instrNode,
65                                        int ruleForNode, short* nts);
66   public:
67     InstructionSelection(TargetMachine &T) : Target(T) {}
68
69     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
70       AU.setPreservesCFG();
71     }
72     
73     bool runOnFunction(Function &F);
74   };
75 }
76
77 // Register the pass...
78 static RegisterLLC<InstructionSelection>
79 X("instselect", "Instruction Selection", createInstructionSelectionPass);
80
81 TmpInstruction::TmpInstruction(Value *s1, Value *s2, const std::string &name)
82   : Instruction(s1->getType(), Instruction::UserOp1, name) {
83   Operands.push_back(Use(s1, this));  // s1 must be nonnull
84   if (s2) {
85     Operands.push_back(Use(s2, this));
86   }
87
88   // TmpInstructions should not be garbage checked.
89   LeakDetector::removeGarbageObject(this);
90 }
91   
92 // Constructor that requires the type of the temporary to be specified.
93 // Both S1 and S2 may be NULL.(
94 TmpInstruction::TmpInstruction(const Type *Ty, Value *s1, Value* s2,
95                                const std::string &name)
96   : Instruction(Ty, Instruction::UserOp1, name) {
97   if (s1) { Operands.push_back(Use(s1, this)); }
98   if (s2) { Operands.push_back(Use(s2, this)); }
99
100   // TmpInstructions should not be garbage checked.
101   LeakDetector::removeGarbageObject(this);
102 }
103
104
105 bool InstructionSelection::runOnFunction(Function &F)
106 {
107   //
108   // Build the instruction trees to be given as inputs to BURG.
109   // 
110   InstrForest instrForest(&F);
111   
112   if (SelectDebugLevel >= Select_DebugInstTrees)
113     {
114       std::cerr << "\n\n*** Input to instruction selection for function "
115                 << F.getName() << "\n\n" << F
116                 << "\n\n*** Instruction trees for function "
117                 << F.getName() << "\n\n";
118       instrForest.dump();
119     }
120   
121   //
122   // Invoke BURG instruction selection for each tree
123   // 
124   for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
125        RI != instrForest.roots_end(); ++RI)
126     {
127       InstructionNode* basicNode = *RI;
128       assert(basicNode->parent() == NULL && "A `root' node has a parent?"); 
129       
130       // Invoke BURM to label each tree node with a state
131       burm_label(basicNode);
132       
133       if (SelectDebugLevel >= Select_DebugBurgTrees)
134         {
135           printcover(basicNode, 1, 0);
136           std::cerr << "\nCover cost == " << treecost(basicNode, 1, 0) <<"\n\n";
137           printMatches(basicNode);
138         }
139       
140       // Then recursively walk the tree to select instructions
141       SelectInstructionsForTree(basicNode, /*goalnt*/1);
142     }
143   
144   //
145   // Create the MachineBasicBlock records and add all of the MachineInstrs
146   // defined in the MachineCodeForInstruction objects to also live in the
147   // MachineBasicBlock objects.
148   // 
149   MachineFunction &MF = MachineFunction::get(&F);
150   for (Function::iterator BI = F.begin(), BE = F.end(); BI != BE; ++BI) {
151     MachineBasicBlock *MCBB = new MachineBasicBlock(BI);
152     MF.getBasicBlockList().push_back(MCBB);
153
154     for (BasicBlock::iterator II = BI->begin(); II != BI->end(); ++II) {
155       MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(II);
156       MCBB->insert(MCBB->end(), mvec.begin(), mvec.end());
157     }
158   }
159
160   // Insert phi elimination code
161   InsertCodeForPhis(F);
162   
163   if (SelectDebugLevel >= Select_PrintMachineCode)
164     {
165       std::cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
166       MachineFunction::get(&F).dump();
167     }
168   
169   return true;
170 }
171
172
173 //-------------------------------------------------------------------------
174 // This method inserts phi elimination code for all BBs in a method
175 //-------------------------------------------------------------------------
176
177 void
178 InstructionSelection::InsertCodeForPhis(Function &F)
179 {
180   // for all basic blocks in function
181   //
182   MachineFunction &MF = MachineFunction::get(&F);
183   for (MachineFunction::iterator BB = MF.begin(); BB != MF.end(); ++BB) {
184     for (BasicBlock::iterator IIt = BB->getBasicBlock()->begin();
185          PHINode *PN = dyn_cast<PHINode>(IIt); ++IIt) {
186       // FIXME: This is probably wrong...
187       Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
188
189       // The leak detector shouldn't track these nodes.  They are not garbage,
190       // even though their parent field is never filled in.
191       //
192       LeakDetector::removeGarbageObject(PhiCpRes);
193
194       // for each incoming value of the phi, insert phi elimination
195       //
196       for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
197         // insert the copy instruction to the predecessor BB
198         vector<MachineInstr*> mvec, CpVec;
199         Target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PhiCpRes,
200                                           mvec);
201         for (vector<MachineInstr*>::iterator MI=mvec.begin();
202              MI != mvec.end(); ++MI) {
203           vector<MachineInstr*> CpVec2 =
204             FixConstantOperandsForInstr(PN, *MI, Target);
205           CpVec2.push_back(*MI);
206           CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
207         }
208         
209         InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
210       }
211       
212       vector<MachineInstr*> mvec;
213       Target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
214       BB->insert(BB->begin(), mvec.begin(), mvec.end());
215     }  // for each Phi Instr in BB
216   } // for all BBs in function
217 }
218
219 //-------------------------------------------------------------------------
220 // Thid method inserts a copy instruction to a predecessor BB as a result
221 // of phi elimination.
222 //-------------------------------------------------------------------------
223
224 void
225 InstructionSelection::InsertPhiElimInstructions(BasicBlock *BB,
226                                             const vector<MachineInstr*>& CpVec)
227
228   Instruction *TermInst = (Instruction*)BB->getTerminator();
229   MachineCodeForInstruction &MC4Term = MachineCodeForInstruction::get(TermInst);
230   MachineInstr *FirstMIOfTerm = MC4Term.front();
231   assert (FirstMIOfTerm && "No Machine Instrs for terminator");
232
233   MachineFunction &MF = MachineFunction::get(BB->getParent());
234
235   // FIXME: if PHI instructions existed in the machine code, this would be
236   // unnecesary.
237   MachineBasicBlock *MBB = 0;
238   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
239     if (I->getBasicBlock() == BB) {
240       MBB = I;
241       break;
242     }
243
244   // find the position of first machine instruction generated by the
245   // terminator of this BB
246   MachineBasicBlock::iterator MCIt =
247     std::find(MBB->begin(), MBB->end(), FirstMIOfTerm);
248
249   assert(MCIt != MBB->end() && "Start inst of terminator not found");
250   
251   // insert the copy instructions just before the first machine instruction
252   // generated for the terminator
253   MBB->insert(MCIt, CpVec.begin(), CpVec.end());
254 }
255
256
257 //---------------------------------------------------------------------------
258 // Function SelectInstructionsForTree 
259 // 
260 // Recursively walk the tree to select instructions.
261 // Do this top-down so that child instructions can exploit decisions
262 // made at the child instructions.
263 // 
264 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
265 // a branch-on-integer-register instruction, then the setle node
266 // can use that information to avoid generating the SUBcc instruction.
267 //
268 // Note that this cannot be done bottom-up because setle must do this
269 // only if it is a child of the branch (otherwise, the result of setle
270 // may be used by multiple instructions).
271 //---------------------------------------------------------------------------
272
273 void 
274 InstructionSelection::SelectInstructionsForTree(InstrTreeNode* treeRoot,
275                                                 int goalnt)
276 {
277   // Get the rule that matches this node.
278   // 
279   int ruleForNode = burm_rule(treeRoot->state, goalnt);
280   
281   if (ruleForNode == 0) {
282     std::cerr << "Could not match instruction tree for instr selection\n";
283     abort();
284   }
285   
286   // Get this rule's non-terminals and the corresponding child nodes (if any)
287   // 
288   short *nts = burm_nts[ruleForNode];
289   
290   // First, select instructions for the current node and rule.
291   // (If this is a list node, not an instruction, then skip this step).
292   // This function is specific to the target architecture.
293   // 
294   if (treeRoot->opLabel != VRegListOp)
295     {
296       vector<MachineInstr*> minstrVec;
297       
298       InstructionNode* instrNode = (InstructionNode*)treeRoot;
299       assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
300       
301       GetInstructionsByRule(instrNode, ruleForNode, nts, Target, minstrVec);
302       
303       MachineCodeForInstruction &mvec = 
304         MachineCodeForInstruction::get(instrNode->getInstruction());
305       mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
306     }
307   
308   // Then, recursively compile the child nodes, if any.
309   // 
310   if (nts[0])
311     { // i.e., there is at least one kid
312       InstrTreeNode* kids[2];
313       int currentRule = ruleForNode;
314       burm_kids(treeRoot, currentRule, kids);
315     
316       // First skip over any chain rules so that we don't visit
317       // the current node again.
318       // 
319       while (ThisIsAChainRule(currentRule))
320         {
321           currentRule = burm_rule(treeRoot->state, nts[0]);
322           nts = burm_nts[currentRule];
323           burm_kids(treeRoot, currentRule, kids);
324         }
325       
326       // Now we have the first non-chain rule so we have found
327       // the actual child nodes.  Recursively compile them.
328       // 
329       for (unsigned i = 0; nts[i]; i++)
330         {
331           assert(i < 2);
332           InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
333           if (nodeType == InstrTreeNode::NTVRegListNode ||
334               nodeType == InstrTreeNode::NTInstructionNode)
335             SelectInstructionsForTree(kids[i], nts[i]);
336         }
337     }
338   
339   // Finally, do any postprocessing on this node after its children
340   // have been translated
341   // 
342   if (treeRoot->opLabel != VRegListOp)
343     PostprocessMachineCodeForTree((InstructionNode*)treeRoot, ruleForNode, nts);
344 }
345
346 //---------------------------------------------------------------------------
347 // Function PostprocessMachineCodeForTree
348 // 
349 // Apply any final cleanups to machine code for the root of a subtree
350 // after selection for all its children has been completed.
351 //
352 void
353 InstructionSelection::PostprocessMachineCodeForTree(InstructionNode* instrNode,
354                                                     int ruleForNode,
355                                                     short* nts) 
356 {
357   // Fix up any constant operands in the machine instructions to either
358   // use an immediate field or to load the constant into a register
359   // Walk backwards and use direct indexes to allow insertion before current
360   // 
361   Instruction* vmInstr = instrNode->getInstruction();
362   MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
363   for (unsigned i = mvec.size(); i != 0; --i)
364     {
365       vector<MachineInstr*> loadConstVec =
366         FixConstantOperandsForInstr(vmInstr, mvec[i-1], Target);
367       
368       mvec.insert(mvec.begin()+i-1, loadConstVec.begin(), loadConstVec.end());
369     }
370 }
371
372
373
374 //===----------------------------------------------------------------------===//
375 // createInstructionSelectionPass - Public entrypoint for instruction selection
376 // and this file as a whole...
377 //
378 Pass *createInstructionSelectionPass(TargetMachine &T) {
379   return new InstructionSelection(T);
380 }