2 //***************************************************************************
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.
13 // 7/02/01 - Vikram Adve - Created
14 //**************************************************************************/
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 #include "llvm/iOther.h"
25 #include "llvm/Target/MachineRegInfo.h"
28 //******************** Internal Data Declarations ************************/
30 // Use a static vector to avoid allocating a new one per VM instruction
31 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
34 enum SelectDebugLevel_t {
36 Select_PrintMachineCode,
37 Select_DebugInstTrees,
38 Select_DebugBurgTrees,
41 // Enable Debug Options to be specified on the command line
42 cl::Enum<enum SelectDebugLevel_t> SelectDebugLevel("dselect", cl::NoFlags,
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);
50 //******************** Forward Function Declarations ***********************/
53 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
55 TargetMachine &target);
57 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
60 TargetMachine &target);
62 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
66 //******************* Externally Visible Functions *************************/
69 //---------------------------------------------------------------------------
70 // Entry point for instruction selection using BURG.
71 // Returns true if instruction selection failed, false otherwise.
72 //---------------------------------------------------------------------------
75 SelectInstructionsForMethod(Method* method, TargetMachine &target)
80 // Build the instruction trees to be given as inputs to BURG.
82 InstrForest instrForest(method);
84 if (SelectDebugLevel >= Select_DebugInstTrees)
86 cout << "\n\n*** Instruction trees for method "
87 << (method->hasName()? method->getName() : "")
93 // Invoke BURG instruction selection for each tree
95 const hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
96 for (hash_set<InstructionNode*>::const_iterator
97 treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
100 InstrTreeNode* basicNode = *treeRootIter;
102 // Invoke BURM to label each tree node with a state
103 burm_label(basicNode);
105 if (SelectDebugLevel >= Select_DebugBurgTrees)
107 printcover(basicNode, 1, 0);
108 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
109 printMatches(basicNode);
112 // Then recursively walk the tree to select instructions
113 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
121 // Record instructions in the vector for each basic block
123 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
125 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
126 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
128 MachineCodeForVMInstr& mvec = (*II)->getMachineInstrVec();
129 for (unsigned i=0; i < mvec.size(); i++)
130 bbMvec.push_back(mvec[i]);
134 // Insert phi elimination code -- added by Ruchira
135 InsertCode4AllPhisInMeth(method, target);
138 if (SelectDebugLevel >= Select_PrintMachineCode)
141 << "*** Machine instructions after INSTRUCTION SELECTION" << endl;
142 MachineCodeForMethod::get(method).dump();
149 //*********************** Private Functions *****************************/
152 //-------------------------------------------------------------------------
153 // Thid method inserts a copy instruction to a predecessor BB as a result
154 // of phi elimination.
155 //-------------------------------------------------------------------------
157 void InsertPhiElimInst(BasicBlock *BB, vector<MachineInstr*>& CopyInstVec) { // bak
159 TerminatorInst *TermInst = BB->getTerminator();
160 MachineCodeForVMInstr &MC4Term = TermInst->getMachineInstrVec();
161 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
163 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
165 // get an iterator to machine instructions in the BB
166 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
167 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
169 // find the position of first machine instruction generated by the
170 // terminator of this BB
171 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt ) ;
173 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
174 assert( (CopyInstVec.size()==1) && "Must be only one copy instr");
176 // insert the copy instruction just before the first machine instruction
177 // generated for the terminator
178 bbMvec.insert( MCIt , CopyInstVec[0] );
180 cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
185 //-------------------------------------------------------------------------
186 // This method inserts phi elimination code for all BBs in a method
187 //-------------------------------------------------------------------------
188 void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target) {
191 // for all basic blocks in method
193 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
195 BasicBlock *BB = *BI;
196 const BasicBlock::InstListType &InstList = BB->getInstList();
197 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
199 // for all instructions in the basic block
201 for( ; IIt != InstList.end(); ++IIt ) {
203 if( (*IIt)->getOpcode() == Instruction::PHINode ) {
205 PHINode *PN = (PHINode *) (*IIt);
207 // for each incoming value of the phi, insert phi elimination
209 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
211 // insert the copy instruction to the predecessor BB
213 vector<MachineInstr*> CopyInstVec;
215 // target.getInstrInfo().CreateCopyInstructionsByType(
216 // target, PN->getIncomingValue(i), PN, CopyInstVec );
219 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PN);
221 CopyInstVec.push_back( MI );
223 InsertPhiElimInst( PN->getIncomingBlock(i), CopyInstVec);
225 // Map the generated copy instruction in pred BB to this phi
226 // (PN->getMachineInstrVec()).push_back( CopyInstVec[0] );
230 else break; // since PHI nodes can only be at the top
232 } // for each Phi Instr in BB
234 } // for all BBs in method
243 //---------------------------------------------------------------------------
244 // Function AppendMachineCodeForVMInstr
246 // Append machine instr sequence to the machine code vec for a VM instr
247 //---------------------------------------------------------------------------
250 AppendMachineCodeForVMInstr(MachineInstr** minstrVec,
252 Instruction* vmInstr)
256 MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
257 mvec.insert(mvec.end(), minstrVec, minstrVec+N);
262 //---------------------------------------------------------------------------
263 // Function PostprocessMachineCodeForTree
265 // Apply any final cleanups to machine code for the root of a subtree
266 // after selection for all its children has been completed.
267 //---------------------------------------------------------------------------
270 PostprocessMachineCodeForTree(InstructionNode* instrNode,
273 TargetMachine &target)
275 // Fix up any constant operands in the machine instructions to either
276 // use an immediate field or to load the constant into a register
277 // Walk backwards and use direct indexes to allow insertion before current
279 Instruction* vmInstr = instrNode->getInstruction();
280 MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
281 for (int i = (int) mvec.size()-1; i >= 0; i--)
283 vector<MachineInstr*> loadConstVec =
284 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
286 if (loadConstVec.size() > 0)
287 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
291 //---------------------------------------------------------------------------
292 // Function SelectInstructionsForTree
294 // Recursively walk the tree to select instructions.
295 // Do this top-down so that child instructions can exploit decisions
296 // made at the child instructions.
298 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
299 // a branch-on-integer-register instruction, then the setle node
300 // can use that information to avoid generating the SUBcc instruction.
302 // Note that this cannot be done bottom-up because setle must do this
303 // only if it is a child of the branch (otherwise, the result of setle
304 // may be used by multiple instructions).
305 //---------------------------------------------------------------------------
308 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
309 TargetMachine &target)
311 // Get the rule that matches this node.
313 int ruleForNode = burm_rule(treeRoot->state, goalnt);
315 if (ruleForNode == 0)
317 cerr << "Could not match instruction tree for instr selection" << endl;
322 // Get this rule's non-terminals and the corresponding child nodes (if any)
324 short *nts = burm_nts[ruleForNode];
326 // First, select instructions for the current node and rule.
327 // (If this is a list node, not an instruction, then skip this step).
328 // This function is specific to the target architecture.
330 if (treeRoot->opLabel != VRegListOp)
332 InstructionNode* instrNode = (InstructionNode*)treeRoot;
333 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
335 unsigned N = GetInstructionsByRule(instrNode, ruleForNode, nts, target,
339 assert(N <= MAX_INSTR_PER_VMINSTR);
340 AppendMachineCodeForVMInstr(minstrVec,N,instrNode->getInstruction());
344 // Then, recursively compile the child nodes, if any.
347 { // i.e., there is at least one kid
348 InstrTreeNode* kids[2];
349 int currentRule = ruleForNode;
350 burm_kids(treeRoot, currentRule, kids);
352 // First skip over any chain rules so that we don't visit
353 // the current node again.
355 while (ThisIsAChainRule(currentRule))
357 currentRule = burm_rule(treeRoot->state, nts[0]);
358 nts = burm_nts[currentRule];
359 burm_kids(treeRoot, currentRule, kids);
362 // Now we have the first non-chain rule so we have found
363 // the actual child nodes. Recursively compile them.
365 for (int i = 0; nts[i]; i++)
368 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
369 if (nodeType == InstrTreeNode::NTVRegListNode ||
370 nodeType == InstrTreeNode::NTInstructionNode)
372 if (SelectInstructionsForTree(kids[i], nts[i], target))
373 return true; // failure
378 // Finally, do any postprocessing on this node after its children
379 // have been translated
381 if (treeRoot->opLabel != VRegListOp)
383 InstructionNode* instrNode = (InstructionNode*)treeRoot;
384 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
387 return false; // success