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/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"
31 //******************** Internal Data Declarations ************************/
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(Function *F, 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(Function *F, TargetMachine &target)
80 // Build the instruction trees to be given as inputs to BURG.
82 InstrForest instrForest(F);
84 if (SelectDebugLevel >= Select_DebugInstTrees)
86 cerr << "\n\n*** Input to instruction selection for function "
87 << F->getName() << "\n\n";
90 cerr << "\n\n*** Instruction trees for function "
91 << F->getName() << "\n\n";
96 // Invoke BURG instruction selection for each tree
98 for (InstrForest::const_root_iterator RI = instrForest.roots_begin();
99 RI != instrForest.roots_end(); ++RI)
101 InstructionNode* basicNode = *RI;
102 assert(basicNode->parent() == NULL && "A `root' node has a parent?");
104 // Invoke BURM to label each tree node with a state
105 burm_label(basicNode);
107 if (SelectDebugLevel >= Select_DebugBurgTrees)
109 printcover(basicNode, 1, 0);
110 cerr << "\nCover cost == " << treecost(basicNode, 1, 0) << "\n\n";
111 printMatches(basicNode);
114 // Then recursively walk the tree to select instructions
115 if (SelectInstructionsForTree(basicNode, /*goalnt*/1, target))
123 // Record instructions in the vector for each basic block
125 for (Function::iterator BI = F->begin(), BE = F->end(); BI != BE; ++BI)
127 MachineCodeForBasicBlock& bbMvec = (*BI)->getMachineInstrVec();
128 for (BasicBlock::iterator II = (*BI)->begin(); II != (*BI)->end(); ++II)
130 MachineCodeForInstruction &mvec =MachineCodeForInstruction::get(*II);
131 for (unsigned i=0; i < mvec.size(); i++)
132 bbMvec.push_back(mvec[i]);
136 // Insert phi elimination code -- added by Ruchira
137 InsertCode4AllPhisInMeth(F, target);
140 if (SelectDebugLevel >= Select_PrintMachineCode)
142 cerr << "\n*** Machine instructions after INSTRUCTION SELECTION\n";
143 MachineCodeForMethod::get(F).dump();
150 //*********************** Private Functions *****************************/
153 //-------------------------------------------------------------------------
154 // Thid method inserts a copy instruction to a predecessor BB as a result
155 // of phi elimination.
156 //-------------------------------------------------------------------------
159 InsertPhiElimInstructions(BasicBlock *BB, const vector<MachineInstr*>& CpVec)
161 Instruction *TermInst = (Instruction*)BB->getTerminator();
162 MachineCodeForInstruction &MC4Term =MachineCodeForInstruction::get(TermInst);
163 MachineInstr *FirstMIOfTerm = *( MC4Term.begin() );
165 assert( FirstMIOfTerm && "No Machine Instrs for terminator" );
167 // get an iterator to machine instructions in the BB
168 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
169 MachineCodeForBasicBlock::iterator MCIt = bbMvec.begin();
171 // find the position of first machine instruction generated by the
172 // terminator of this BB
173 for( ; (MCIt != bbMvec.end()) && (*MCIt != FirstMIOfTerm) ; ++MCIt )
175 assert( MCIt != bbMvec.end() && "Start inst of terminator not found");
177 // insert the copy instructions just before the first machine instruction
178 // generated for the terminator
179 bbMvec.insert(MCIt, CpVec.begin(), CpVec.end());
181 //cerr << "\nPhiElimination copy inst: " << *CopyInstVec[0];
185 //-------------------------------------------------------------------------
186 // This method inserts phi elimination code for all BBs in a method
187 //-------------------------------------------------------------------------
190 InsertCode4AllPhisInMeth(Function *F, TargetMachine &target)
192 // for all basic blocks in function
194 for (Function::iterator BI = F->begin(); BI != F->end(); ++BI) {
196 BasicBlock *BB = *BI;
197 const BasicBlock::InstListType &InstList = BB->getInstList();
198 BasicBlock::InstListType::const_iterator IIt = InstList.begin();
200 // for all instructions in the basic block
202 for( ; IIt != InstList.end(); ++IIt ) {
204 if (PHINode *PN = dyn_cast<PHINode>(*IIt)) {
205 // FIXME: This is probably wrong...
206 Value *PhiCpRes = new PHINode(PN->getType(), "PhiCp:");
208 // for each incoming value of the phi, insert phi elimination
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,
215 for (vector<MachineInstr*>::iterator MI=mvec.begin();
216 MI != mvec.end(); ++MI)
218 vector<MachineInstr*> CpVec2 =
219 FixConstantOperandsForInstr(PN, *MI, target);
220 CpVec2.push_back(*MI);
221 CpVec.insert(CpVec.end(), CpVec2.begin(), CpVec2.end());
224 InsertPhiElimInstructions(PN->getIncomingBlock(i), CpVec);
227 vector<MachineInstr*> mvec;
228 target.getRegInfo().cpValue2Value(PhiCpRes, PN, mvec);
230 // get an iterator to machine instructions in the BB
231 MachineCodeForBasicBlock& bbMvec = BB->getMachineInstrVec();
233 bbMvec.insert( bbMvec.begin(), mvec.begin(), mvec.end());
235 else break; // since PHI nodes can only be at the top
237 } // for each Phi Instr in BB
238 } // for all BBs in function
242 //---------------------------------------------------------------------------
243 // Function PostprocessMachineCodeForTree
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 //---------------------------------------------------------------------------
250 PostprocessMachineCodeForTree(InstructionNode* instrNode,
253 TargetMachine &target)
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
259 Instruction* vmInstr = instrNode->getInstruction();
260 MachineCodeForInstruction &mvec = MachineCodeForInstruction::get(vmInstr);
261 for (int i = (int) mvec.size()-1; i >= 0; i--)
263 std::vector<MachineInstr*> loadConstVec =
264 FixConstantOperandsForInstr(vmInstr, mvec[i], target);
266 if (loadConstVec.size() > 0)
267 mvec.insert(mvec.begin()+i, loadConstVec.begin(), loadConstVec.end());
271 //---------------------------------------------------------------------------
272 // Function SelectInstructionsForTree
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.
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.
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 //---------------------------------------------------------------------------
288 SelectInstructionsForTree(InstrTreeNode* treeRoot, int goalnt,
289 TargetMachine &target)
291 // Get the rule that matches this node.
293 int ruleForNode = burm_rule(treeRoot->state, goalnt);
295 if (ruleForNode == 0)
297 cerr << "Could not match instruction tree for instr selection\n";
302 // Get this rule's non-terminals and the corresponding child nodes (if any)
304 short *nts = burm_nts[ruleForNode];
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.
310 if (treeRoot->opLabel != VRegListOp)
312 vector<MachineInstr*> minstrVec;
314 InstructionNode* instrNode = (InstructionNode*)treeRoot;
315 assert(instrNode->getNodeType() == InstrTreeNode::NTInstructionNode);
317 GetInstructionsByRule(instrNode, ruleForNode, nts, target, minstrVec);
319 MachineCodeForInstruction &mvec =
320 MachineCodeForInstruction::get(instrNode->getInstruction());
321 mvec.insert(mvec.end(), minstrVec.begin(), minstrVec.end());
324 // Then, recursively compile the child nodes, if any.
327 { // i.e., there is at least one kid
328 InstrTreeNode* kids[2];
329 int currentRule = ruleForNode;
330 burm_kids(treeRoot, currentRule, kids);
332 // First skip over any chain rules so that we don't visit
333 // the current node again.
335 while (ThisIsAChainRule(currentRule))
337 currentRule = burm_rule(treeRoot->state, nts[0]);
338 nts = burm_nts[currentRule];
339 burm_kids(treeRoot, currentRule, kids);
342 // Now we have the first non-chain rule so we have found
343 // the actual child nodes. Recursively compile them.
345 for (int i = 0; nts[i]; i++)
348 InstrTreeNode::InstrTreeNodeType nodeType = kids[i]->getNodeType();
349 if (nodeType == InstrTreeNode::NTVRegListNode ||
350 nodeType == InstrTreeNode::NTInstructionNode)
352 if (SelectInstructionsForTree(kids[i], nts[i], target))
353 return true; // failure
358 // Finally, do any postprocessing on this node after its children
359 // have been translated
361 if (treeRoot->opLabel != VRegListOp)
363 InstructionNode* instrNode = (InstructionNode*)treeRoot;
364 PostprocessMachineCodeForTree(instrNode, ruleForNode, nts, target);
367 return false; // success