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/Instruction.h"
21 #include "llvm/BasicBlock.h"
22 #include "llvm/Method.h"
23 #include "llvm/iPHINode.h"
24 #include "llvm/Target/MachineRegInfo.h"
25 #include "Support/CommandLine.h"
29 //******************** Internal Data Declarations ************************/
31 // Use a static vector to avoid allocating a new one per VM instruction
32 static MachineInstr* minstrVec[MAX_INSTR_PER_VMINSTR];
35 enum SelectDebugLevel_t {
37 Select_PrintMachineCode,
38 Select_DebugInstTrees,
39 Select_DebugBurgTrees,
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);
51 //******************** Forward Function Declarations ***********************/
54 static bool SelectInstructionsForTree (InstrTreeNode* treeRoot,
56 TargetMachine &target);
58 static void PostprocessMachineCodeForTree(InstructionNode* instrNode,
61 TargetMachine &target);
63 static void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target);
67 //******************* Externally Visible Functions *************************/
70 //---------------------------------------------------------------------------
71 // Entry point for instruction selection using BURG.
72 // Returns true if instruction selection failed, false otherwise.
73 //---------------------------------------------------------------------------
76 SelectInstructionsForMethod(Method* method, TargetMachine &target)
81 // Build the instruction trees to be given as inputs to BURG.
83 InstrForest instrForest(method);
85 if (SelectDebugLevel >= Select_DebugInstTrees)
87 cout << "\n\n*** Instruction trees for method "
88 << (method->hasName()? method->getName() : "")
94 // Invoke BURG instruction selection for each tree
96 const hash_set<InstructionNode*> &treeRoots = instrForest.getRootSet();
97 for (hash_set<InstructionNode*>::const_iterator
98 treeRootIter = treeRoots.begin(); treeRootIter != treeRoots.end();
101 InstrTreeNode* basicNode = *treeRootIter;
103 // Invoke BURM to label each tree node with a state
104 burm_label(basicNode);
106 if (SelectDebugLevel >= Select_DebugBurgTrees)
108 printcover(basicNode, 1, 0);
109 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
110 printMatches(basicNode);
113 // Then recursively walk the tree to select instructions
114 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
122 // Record instructions in the vector for each basic block
124 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI)
126 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
127 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
129 MachineCodeForVMInstr& mvec = (*II)->getMachineInstrVec();
130 for (unsigned i=0; i < mvec.size(); i++)
131 bbMvec.push_back(mvec[i]);
135 // Insert phi elimination code -- added by Ruchira
136 InsertCode4AllPhisInMeth(method, target);
139 if (SelectDebugLevel >= Select_PrintMachineCode)
142 << "*** Machine instructions after INSTRUCTION SELECTION" << endl;
143 MachineCodeForMethod::get(method).dump();
150 //*********************** Private Functions *****************************/
153 //-------------------------------------------------------------------------
154 // Thid method inserts a copy instruction to a predecessor BB as a result
155 // of phi elimination.
156 //-------------------------------------------------------------------------
158 void InsertPhiElimInst(BasicBlock *BB, MachineInstr *CpMI) {
160 TerminatorInst *TermInst = BB->getTerminator();
161 MachineCodeForVMInstr &MC4Term = TermInst->getMachineInstrVec();
162 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
164 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
166 // get an iterator to machine instructions in the BB
167 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
168 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
170 // find the position of first machine instruction generated by the
171 // terminator of this BB
172 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt ) ;
174 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
176 // insert the copy instruction just before the first machine instruction
177 // generated for the terminator
178 bbMvec.insert( MCIt , CpMI );
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;
216 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i), PN);
218 InsertPhiElimInst( PN->getIncomingBlock(i), CpMI);
221 else break; // since PHI nodes can only be at the top
223 } // for each Phi Instr in BB
225 } // for all BBs in method
231 //-------------------------------------------------------------------------
232 // This method inserts phi elimination code for all BBs in a method
233 //-------------------------------------------------------------------------
234 void InsertCode4AllPhisInMeth(Method *method, TargetMachine &target) {
237 // for all basic blocks in method
239 for (Method::iterator BI = method->begin(); BI != method->end(); ++BI) {
241 BasicBlock *BB = *BI;
242 const BasicBlock::InstListType &InstList = BB->getInstList();
243 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
245 // for all instructions in the basic block
247 for( ; IIt != InstList.end(); ++IIt ) {
249 if( (*IIt)->getOpcode() == Instruction::PHINode ) {
251 PHINode *PN = (PHINode *) (*IIt);
253 Value *PhiCpRes = new Value(PN->getType(), PN->getValueType());
255 string *Name = new string("PhiCp:");
256 (*Name) += (int) PhiCpRes;
257 PhiCpRes->setName( *Name );
260 // for each incoming value of the phi, insert phi elimination
262 for (unsigned i = 0; i < PN->getNumIncomingValues(); ++i) {
264 // insert the copy instruction to the predecessor BB
267 target.getRegInfo().cpValue2Value(PN->getIncomingValue(i),
270 InsertPhiElimInst(PN->getIncomingBlock(i), CpMI);
275 MachineInstr *CpMI2 =
276 target.getRegInfo().cpValue2Value(PhiCpRes, PN);
278 // get an iterator to machine instructions in the BB
279 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
281 bbMvec.insert( bbMvec.begin(), CpMI2);
285 else break; // since PHI nodes can only be at the top
287 } // for each Phi Instr in BB
289 } // for all BBs in method
301 //---------------------------------------------------------------------------
302 // Function AppendMachineCodeForVMInstr
304 // Append machine instr sequence to the machine code vec for a VM instr
305 //---------------------------------------------------------------------------
308 AppendMachineCodeForVMInstr(MachineInstr** minstrVec,
310 Instruction* vmInstr)
314 MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
315 mvec.insert(mvec.end(), minstrVec, minstrVec+N);
320 //---------------------------------------------------------------------------
321 // Function PostprocessMachineCodeForTree
323 // Apply any final cleanups to machine code for the root of a subtree
324 // after selection for all its children has been completed.
325 //---------------------------------------------------------------------------
328 PostprocessMachineCodeForTree(InstructionNode* instrNode,
331 TargetMachine &target)
333 // Fix up any constant operands in the machine instructions to either
334 // use an immediate field or to load the constant into a register
335 // Walk backwards and use direct indexes to allow insertion before current
337 Instruction* vmInstr = instrNode->getInstruction();
338 MachineCodeForVMInstr& mvec = vmInstr->getMachineInstrVec();
339 for (int i = (int) mvec.size()-1; i >= 0; i--)
341 vector<MachineInstr*> loadConstVec =
342 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
344 if (loadConstVec.size() > 0)
345 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
349 //---------------------------------------------------------------------------
350 // Function SelectInstructionsForTree
352 // Recursively walk the tree to select instructions.
353 // Do this top-down so that child instructions can exploit decisions
354 // made at the child instructions.
356 // E.g., if br(setle(reg,const)) decides the constant is 0 and uses
357 // a branch-on-integer-register instruction, then the setle node
358 // can use that information to avoid generating the SUBcc instruction.
360 // Note that this cannot be done bottom-up because setle must do this
361 // only if it is a child of the branch (otherwise, the result of setle
362 // may be used by multiple instructions).
363 //---------------------------------------------------------------------------
366 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
367 TargetMachine &target)
369 // Get the rule that matches this node.
371 int ruleForNode = burm_rule(treeRoot->state, goalnt);
373 if (ruleForNode == 0)
375 cerr << "Could not match instruction tree for instr selection" << endl;
380 // Get this rule's non-terminals and the corresponding child nodes (if any)
382 short *nts = burm_nts[ruleForNode];
384 // First, select instructions for the current node and rule.
385 // (If this is a list node, not an instruction, then skip this step).
386 // This function is specific to the target architecture.
388 if (treeRoot->opLabel != VRegListOp)
390 InstructionNode* instrNode = (InstructionNode*)treeRoot;
391 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
393 unsigned N = GetInstructionsByRule(instrNode, ruleForNode, nts, target,
397 assert(N <= MAX_INSTR_PER_VMINSTR);
398 AppendMachineCodeForVMInstr(minstrVec,N,instrNode->getInstruction());
402 // Then, recursively compile the child nodes, if any.
405 { // i.e., there is at least one kid
406 InstrTreeNode* kids[2];
407 int currentRule = ruleForNode;
408 burm_kids(treeRoot, currentRule, kids);
410 // First skip over any chain rules so that we don't visit
411 // the current node again.
413 while (ThisIsAChainRule(currentRule))
415 currentRule = burm_rule(treeRoot->state, nts[0]);
416 nts = burm_nts[currentRule];
417 burm_kids(treeRoot, currentRule, kids);
420 // Now we have the first non-chain rule so we have found
421 // the actual child nodes. Recursively compile them.
423 for (int i = 0; nts[i]; i++)
426 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
427 if (nodeType == InstrTreeNode::NTVRegListNode ||
428 nodeType == InstrTreeNode::NTInstructionNode)
430 if (SelectInstructionsForTree(kids[i], nts[i], target))
431 return true; // failure
436 // Finally, do any postprocessing on this node after its children
437 // have been translated
439 if (treeRoot->opLabel != VRegListOp)
441 InstructionNode* instrNode = (InstructionNode*)treeRoot;
442 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
445 return false; // success