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