Rewrote uses of deprecated `MachineFunction::get(BasicBlock *BB)'.
[oota-llvm.git] / lib / Target / SparcV9 / InstrSelection / InstrForest.cpp
1 //===-- InstrForest.cpp - Build instruction forest for inst selection -----===//
2 //
3 //  The key goal is to group instructions into a single
4 //  tree if one or more of them might be potentially combined into a single
5 //  complex instruction in the target machine.
6 //  Since this grouping is completely machine-independent, we do it as
7 //  aggressive as possible to exploit any possible taret instructions.
8 //  In particular, we group two instructions O and I if:
9 //      (1) Instruction O computes an operand used by instruction I,
10 //  and (2) O and I are part of the same basic block,
11 //  and (3) O has only a single use, viz., I.
12 // 
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/CodeGen/InstrForest.h"
16 #include "llvm/CodeGen/MachineCodeForInstruction.h"
17 #include "llvm/Function.h"
18 #include "llvm/iTerminators.h"
19 #include "llvm/iMemory.h"
20 #include "llvm/Constant.h"
21 #include "llvm/Type.h"
22 #include "llvm/CodeGen/MachineInstr.h"
23 #include "Support/STLExtras.h"
24 #include <alloca.h>
25 using std::cerr;
26 using std::vector;
27
28 //------------------------------------------------------------------------ 
29 // class InstrTreeNode
30 //------------------------------------------------------------------------ 
31
32 void
33 InstrTreeNode::dump(int dumpChildren, int indent) const
34 {
35   dumpNode(indent);
36   
37   if (dumpChildren)
38     {
39       if (LeftChild)
40         LeftChild->dump(dumpChildren, indent+1);
41       if (RightChild)
42         RightChild->dump(dumpChildren, indent+1);
43     }
44 }
45
46
47 InstructionNode::InstructionNode(Instruction* I)
48   : InstrTreeNode(NTInstructionNode, I),
49     codeIsFoldedIntoParent(false)
50 {
51   opLabel = I->getOpcode();
52
53   // Distinguish special cases of some instructions such as Ret and Br
54   // 
55   if (opLabel == Instruction::Ret && cast<ReturnInst>(I)->getReturnValue())
56     {
57       opLabel = RetValueOp;                      // ret(value) operation
58     }
59   else if (opLabel ==Instruction::Br && !cast<BranchInst>(I)->isUnconditional())
60     {
61       opLabel = BrCondOp;               // br(cond) operation
62     }
63   else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT)
64     {
65       opLabel = SetCCOp;                // common label for all SetCC ops
66     }
67   else if (opLabel == Instruction::Alloca && I->getNumOperands() > 0)
68     {
69       opLabel = AllocaN;                 // Alloca(ptr, N) operation
70     }
71   else if (opLabel == Instruction::GetElementPtr &&
72            cast<GetElementPtrInst>(I)->hasIndices())
73     {
74       opLabel = opLabel + 100;           // getElem with index vector
75     }
76   else if (opLabel == Instruction::Xor &&
77            BinaryOperator::isNot(I))
78     {
79       opLabel = (I->getType() == Type::BoolTy)?  NotOp  // boolean Not operator
80                                               : BNotOp; // bitwise Not operator
81     }
82   else if (opLabel == Instruction::And ||
83            opLabel == Instruction::Or ||
84            opLabel == Instruction::Xor)
85     {
86       // Distinguish bitwise operators from logical operators!
87       if (I->getType() != Type::BoolTy)
88         opLabel = opLabel + 100;         // bitwise operator
89     }
90   else if (opLabel == Instruction::Cast)
91     {
92       const Type *ITy = I->getType();
93       switch(ITy->getPrimitiveID())
94         {
95         case Type::BoolTyID:    opLabel = ToBoolTy;    break;
96         case Type::UByteTyID:   opLabel = ToUByteTy;   break;
97         case Type::SByteTyID:   opLabel = ToSByteTy;   break;
98         case Type::UShortTyID:  opLabel = ToUShortTy;  break;
99         case Type::ShortTyID:   opLabel = ToShortTy;   break;
100         case Type::UIntTyID:    opLabel = ToUIntTy;    break;
101         case Type::IntTyID:     opLabel = ToIntTy;     break;
102         case Type::ULongTyID:   opLabel = ToULongTy;   break;
103         case Type::LongTyID:    opLabel = ToLongTy;    break;
104         case Type::FloatTyID:   opLabel = ToFloatTy;   break;
105         case Type::DoubleTyID:  opLabel = ToDoubleTy;  break;
106         case Type::ArrayTyID:   opLabel = ToArrayTy;   break;
107         case Type::PointerTyID: opLabel = ToPointerTy; break;
108         default:
109           // Just use `Cast' opcode otherwise. It's probably ignored.
110           break;
111         }
112     }
113 }
114
115
116 void
117 InstructionNode::dumpNode(int indent) const
118 {
119   for (int i=0; i < indent; i++)
120     cerr << "    ";
121   cerr << getInstruction()->getOpcodeName()
122        << " [label " << getOpLabel() << "]" << "\n";
123 }
124
125
126 void
127 VRegListNode::dumpNode(int indent) const
128 {
129   for (int i=0; i < indent; i++)
130     cerr << "    ";
131   
132   cerr << "List" << "\n";
133 }
134
135
136 void
137 VRegNode::dumpNode(int indent) const
138 {
139   for (int i=0; i < indent; i++)
140     cerr << "    ";
141   
142   cerr << "VReg " << getValue() << "\t(type "
143        << (int) getValue()->getValueType() << ")" << "\n";
144 }
145
146 void
147 ConstantNode::dumpNode(int indent) const
148 {
149   for (int i=0; i < indent; i++)
150     cerr << "    ";
151   
152   cerr << "Constant " << getValue() << "\t(type "
153        << (int) getValue()->getValueType() << ")" << "\n";
154 }
155
156 void
157 LabelNode::dumpNode(int indent) const
158 {
159   for (int i=0; i < indent; i++)
160     cerr << "    ";
161   
162   cerr << "Label " << getValue() << "\n";
163 }
164
165 //------------------------------------------------------------------------
166 // class InstrForest
167 // 
168 // A forest of instruction trees, usually for a single method.
169 //------------------------------------------------------------------------ 
170
171 InstrForest::InstrForest(Function *F)
172 {
173   for (Function::iterator BB = F->begin(), FE = F->end(); BB != FE; ++BB) {
174     for(BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
175       buildTreeForInstruction(I);
176   }
177 }
178
179 InstrForest::~InstrForest()
180 {
181   for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
182 }
183
184 void
185 InstrForest::dump() const
186 {
187   for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
188     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
189 }
190
191 inline void
192 InstrForest::eraseRoot(InstructionNode* node)
193 {
194   for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
195        RI != RE; ++RI)
196     if (*RI == node)
197       treeRoots.erase(RI.base()-1);
198 }
199
200 inline void
201 InstrForest::noteTreeNodeForInstr(Instruction *instr,
202                                   InstructionNode *treeNode)
203 {
204   (*this)[instr] = treeNode;
205   treeRoots.push_back(treeNode);        // mark node as root of a new tree
206 }
207
208
209 inline void
210 InstrForest::setLeftChild(InstrTreeNode *parent, InstrTreeNode *child)
211 {
212   parent->LeftChild = child;
213   child->Parent = parent;
214   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
215     eraseRoot(instrNode); // no longer a tree root
216 }
217
218 inline void
219 InstrForest::setRightChild(InstrTreeNode *parent, InstrTreeNode *child)
220 {
221   parent->RightChild = child;
222   child->Parent = parent;
223   if (InstructionNode* instrNode = dyn_cast<InstructionNode>(child))
224     eraseRoot(instrNode); // no longer a tree root
225 }
226
227
228 InstructionNode*
229 InstrForest::buildTreeForInstruction(Instruction *instr)
230 {
231   InstructionNode *treeNode = getTreeNodeForInstr(instr);
232   if (treeNode)
233     {
234       // treeNode has already been constructed for this instruction
235       assert(treeNode->getInstruction() == instr);
236       return treeNode;
237     }
238   
239   // Otherwise, create a new tree node for this instruction.
240   // 
241   treeNode = new InstructionNode(instr);
242   noteTreeNodeForInstr(instr, treeNode);
243   
244   if (instr->getOpcode() == Instruction::Call)
245     { // Operands of call instruction
246       return treeNode;
247     }
248   
249   // If the instruction has more than 2 instruction operands,
250   // then we need to create artificial list nodes to hold them.
251   // (Note that we only count operands that get tree nodes, and not
252   // others such as branch labels for a branch or switch instruction.)
253   //
254   // To do this efficiently, we'll walk all operands, build treeNodes
255   // for all appropriate operands and save them in an array.  We then
256   // insert children at the end, creating list nodes where needed.
257   // As a performance optimization, allocate a child array only
258   // if a fixed array is too small.
259   // 
260   int numChildren = 0;
261   InstrTreeNode **childArray =
262     (InstrTreeNode **)alloca(instr->getNumOperands()*sizeof(InstrTreeNode *));
263   
264   //
265   // Walk the operands of the instruction
266   // 
267   for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end(); ++O)
268     {
269       Value* operand = *O;
270       
271       // Check if the operand is a data value, not an branch label, type,
272       // method or module.  If the operand is an address type (i.e., label
273       // or method) that is used in an non-branching operation, e.g., `add'.
274       // that should be considered a data value.
275     
276       // Check latter condition here just to simplify the next IF.
277       bool includeAddressOperand =
278         (isa<BasicBlock>(operand) || isa<Function>(operand))
279         && !instr->isTerminator();
280     
281       if (includeAddressOperand || isa<Instruction>(operand) ||
282           isa<Constant>(operand) || isa<Argument>(operand) ||
283           isa<GlobalVariable>(operand))
284         {
285           // This operand is a data value
286         
287           // An instruction that computes the incoming value is added as a
288           // child of the current instruction if:
289           //   the value has only a single use
290           //   AND both instructions are in the same basic block.
291           //   AND the current instruction is not a PHI (because the incoming
292           //            value is conceptually in a predecessor block,
293           //            even though it may be in the same static block)
294           // 
295           // (Note that if the value has only a single use (viz., `instr'),
296           //  the def of the value can be safely moved just before instr
297           //  and therefore it is safe to combine these two instructions.)
298           // 
299           // In all other cases, the virtual register holding the value
300           // is used directly, i.e., made a child of the instruction node.
301           // 
302           InstrTreeNode* opTreeNode;
303           if (isa<Instruction>(operand) && operand->use_size() == 1 &&
304               cast<Instruction>(operand)->getParent() == instr->getParent() &&
305               instr->getOpcode() != Instruction::PHINode &&
306               instr->getOpcode() != Instruction::Call)
307             {
308               // Recursively create a treeNode for it.
309               opTreeNode = buildTreeForInstruction((Instruction*)operand);
310             }
311           else if (Constant *CPV = dyn_cast<Constant>(operand))
312             {
313               // Create a leaf node for a constant
314               opTreeNode = new ConstantNode(CPV);
315             }
316           else
317             {
318               // Create a leaf node for the virtual register
319               opTreeNode = new VRegNode(operand);
320             }
321
322           childArray[numChildren++] = opTreeNode;
323         }
324     }
325   
326   //-------------------------------------------------------------------- 
327   // Add any selected operands as children in the tree.
328   // Certain instructions can have more than 2 in some instances (viz.,
329   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
330   // array or struct). Make the operands of every such instruction into
331   // a right-leaning binary tree with the operand nodes at the leaves
332   // and VRegList nodes as internal nodes.
333   //-------------------------------------------------------------------- 
334   
335   InstrTreeNode *parent = treeNode;
336   
337   if (numChildren > 2)
338     {
339       unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
340       assert(instrOpcode == Instruction::PHINode ||
341              instrOpcode == Instruction::Call ||
342              instrOpcode == Instruction::Load ||
343              instrOpcode == Instruction::Store ||
344              instrOpcode == Instruction::GetElementPtr);
345     }
346   
347   // Insert the first child as a direct child
348   if (numChildren >= 1)
349     setLeftChild(parent, childArray[0]);
350
351   int n;
352   
353   // Create a list node for children 2 .. N-1, if any
354   for (n = numChildren-1; n >= 2; n--)
355     {
356       // We have more than two children
357       InstrTreeNode *listNode = new VRegListNode();
358       setRightChild(parent, listNode);
359       setLeftChild(listNode, childArray[numChildren - n]);
360       parent = listNode;
361     }
362   
363   // Now insert the last remaining child (if any).
364   if (numChildren >= 2)
365     {
366       assert(n == 1);
367       setRightChild(parent, childArray[numChildren - 1]);
368     }
369   
370   return treeNode;
371 }