Moved inline/llvm/Tools/* to include/llvm/Support/*
[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,
42                              Value* _val)
43   : treeNodeType(nodeType),
44     val(_val)
45 {
46   basicNode.leftChild = NULL;
47   basicNode.rightChild = NULL;
48   basicNode.parent = NULL;
49   basicNode.opLabel = InvalidOp;
50   basicNode.treeNodePtr = this;
51 }
52
53 InstrTreeNode::~InstrTreeNode()
54 {}
55
56
57 void
58 InstrTreeNode::dump(int dumpChildren,
59                     int indent) const
60 {
61   this->dumpNode(indent);
62   
63   if (dumpChildren)
64     {
65       if (leftChild())
66         leftChild()->dump(dumpChildren, indent+1);
67       if (rightChild())
68         rightChild()->dump(dumpChildren, indent+1);
69     }
70 }
71
72
73 InstructionNode::InstructionNode(Instruction* _instr)
74   : InstrTreeNode(NTInstructionNode, _instr)
75 {
76   OpLabel opLabel = _instr->getOpcode();
77
78   // Distinguish special cases of some instructions such as Ret and Br
79   // 
80   if (opLabel == Instruction::Ret && ((ReturnInst*) _instr)->getReturnValue())
81     {
82       opLabel = RetValueOp;              // ret(value) operation
83     }
84   else if (opLabel == Instruction::Br && ! ((BranchInst*) _instr)->isUnconditional())
85     {
86       opLabel = BrCondOp;               // br(cond) operation
87     }
88   else if (opLabel >= Instruction::SetEQ && opLabel <= Instruction::SetGT)
89     {
90       opLabel = SetCCOp;                // common label for all SetCC ops
91     }
92   else if (opLabel == Instruction::Alloca && _instr->getNumOperands() > 0)
93     {
94       opLabel = AllocaN;                 // Alloca(ptr, N) operation
95     }
96   else if ((opLabel == Instruction::Load ||
97             opLabel == Instruction::GetElementPtr)
98            && ((MemAccessInst*)_instr)->getFirstOffsetIdx() > 0)
99     {
100       opLabel = opLabel + 100;           // load/getElem with index vector
101     }
102   else if (opLabel == Instruction::Cast)
103     {
104       const Type* instrValueType = _instr->getType();
105       switch(instrValueType->getPrimitiveID())
106         {
107         case Type::BoolTyID:    opLabel = ToBoolTy;  break;
108         case Type::UByteTyID:   opLabel = ToUByteTy; break;
109         case Type::SByteTyID:   opLabel = ToSByteTy; break;
110         case Type::UShortTyID:  opLabel = ToUShortTy; break;
111         case Type::ShortTyID:   opLabel = ToShortTy; break;
112         case Type::UIntTyID:    opLabel = ToUIntTy; break;
113         case Type::IntTyID:     opLabel = ToIntTy; break;
114         case Type::ULongTyID:   opLabel = ToULongTy; break;
115         case Type::LongTyID:    opLabel = ToLongTy; break;
116         case Type::FloatTyID:   opLabel = ToFloatTy; break;
117         case Type::DoubleTyID:  opLabel = ToDoubleTy; break;
118         default:
119           if (instrValueType->isArrayType())
120             opLabel = ToArrayTy;
121           else if (instrValueType->isPointerType())
122             opLabel = ToPointerTy;
123           else
124             ; // Just use `Cast' opcode otherwise. It's probably ignored.
125           break;
126         }
127     }
128   
129   basicNode.opLabel = opLabel;
130 }
131
132 void
133 InstructionNode::reverseBinaryArgumentOrder()
134 {
135   assert(getInstruction()->isBinaryOp());
136   
137   // switch arguments for the instruction
138   ((BinaryOperator*) getInstruction())->swapOperands();
139   
140   // switch arguments for this tree node itself
141   BasicTreeNode* leftCopy = basicNode.leftChild;
142   basicNode.leftChild = basicNode.rightChild;
143   basicNode.rightChild = leftCopy;
144 }
145
146 void
147 InstructionNode::dumpNode(int indent) const
148 {
149   for (int i=0; i < indent; i++)
150     cout << "    ";
151   
152   cout << getInstruction()->getOpcodeName();
153   
154   const vector<MachineInstr*>& mvec = getInstruction()->getMachineInstrVec();
155   if (mvec.size() > 0)
156     cout << "\tMachine Instructions:  ";
157   for (unsigned int i=0; i < mvec.size(); i++)
158     {
159       mvec[i]->dump(0);
160       if (i < mvec.size() - 1)
161         cout << ";  ";
162     }
163   
164   cout << endl;
165 }
166
167
168 VRegListNode::VRegListNode()
169   : InstrTreeNode(NTVRegListNode, NULL)
170 {
171   basicNode.opLabel = VRegListOp;
172 }
173
174 void
175 VRegListNode::dumpNode(int indent) const
176 {
177   for (int i=0; i < indent; i++)
178     cout << "    ";
179   
180   cout << "List" << endl;
181 }
182
183
184 VRegNode::VRegNode(Value* _val)
185   : InstrTreeNode(NTVRegNode, _val)
186 {
187   basicNode.opLabel = VRegNodeOp;
188 }
189
190 void
191 VRegNode::dumpNode(int indent) const
192 {
193   for (int i=0; i < indent; i++)
194     cout << "    ";
195   
196   cout << "VReg " << getValue() << "\t(type "
197        << (int) getValue()->getValueType() << ")" << endl;
198 }
199
200
201 ConstantNode::ConstantNode(ConstPoolVal* constVal)
202   : InstrTreeNode(NTConstNode, constVal)
203 {
204   basicNode.opLabel = ConstantNodeOp;
205 }
206
207 void
208 ConstantNode::dumpNode(int indent) const
209 {
210   for (int i=0; i < indent; i++)
211     cout << "    ";
212   
213   cout << "Constant " << getValue() << "\t(type "
214        << (int) getValue()->getValueType() << ")" << endl;
215 }
216
217
218 LabelNode::LabelNode(BasicBlock* _bblock)
219   : InstrTreeNode(NTLabelNode, _bblock)
220 {
221   basicNode.opLabel = LabelNodeOp;
222 }
223
224 void
225 LabelNode::dumpNode(int indent) const
226 {
227   for (int i=0; i < indent; i++)
228     cout << "    ";
229   
230   cout << "Label " << getValue() << endl;
231 }
232
233 //------------------------------------------------------------------------
234 // class InstrForest
235 // 
236 // A forest of instruction trees, usually for a single method.
237 //------------------------------------------------------------------------ 
238
239 void
240 InstrForest::buildTreesForMethod(Method *method)
241 {
242   for (Method::inst_iterator instrIter = method->inst_begin();
243        instrIter != method->inst_end();
244        ++instrIter)
245     {
246       Instruction *instr = *instrIter;
247       if (! instr->isPHINode())
248         (void) this->buildTreeForInstruction(instr);
249     } 
250 }
251
252
253 void
254 InstrForest::dump() const
255 {
256   for (hash_set<InstructionNode*>::const_iterator
257          treeRootIter = treeRoots.begin();
258        treeRootIter != treeRoots.end();
259        ++treeRootIter)
260     {
261       (*treeRootIter)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
262     }
263 }
264
265 inline void
266 InstrForest::noteTreeNodeForInstr(Instruction* instr,
267                                   InstructionNode* treeNode)
268 {
269   assert(treeNode->getNodeType() == InstrTreeNode::NTInstructionNode);
270   (*this)[instr] = treeNode;
271   treeRoots.insert(treeNode);           // mark node as root of a new tree
272 }
273
274
275 inline void
276 InstrForest::setLeftChild(InstrTreeNode* parent, InstrTreeNode* child)
277 {
278   parent->basicNode.leftChild = & child->basicNode;
279   child->basicNode.parent = & parent->basicNode;
280   if (child->getNodeType() == InstrTreeNode::NTInstructionNode)
281     treeRoots.erase((InstructionNode*) child);  // no longer a tree root
282 }
283
284
285 inline void
286 InstrForest::setRightChild(InstrTreeNode* parent, InstrTreeNode* child)
287 {
288   parent->basicNode.rightChild = & child->basicNode;
289   child->basicNode.parent = & parent->basicNode;
290   if (child->getNodeType() == InstrTreeNode::NTInstructionNode)
291     treeRoots.erase((InstructionNode*) child);  // no longer a tree root
292 }
293
294
295 InstructionNode*
296 InstrForest::buildTreeForInstruction(Instruction* instr)
297 {
298   InstructionNode* treeNode = this->getTreeNodeForInstr(instr);
299   if (treeNode != NULL)
300     {// treeNode has already been constructed for this instruction
301       assert(treeNode->getInstruction() == instr);
302       return treeNode;
303     }
304   
305   // Otherwise, create a new tree node for this instruction.
306   // 
307   treeNode = new InstructionNode(instr);
308   this->noteTreeNodeForInstr(instr, treeNode);
309   
310   // If the instruction has more than 2 instruction operands,
311   // then we will not add any children.  This assumes that instructions
312   // like 'call' that have more than 2 instruction operands do not
313   // ever get combined with the instructions that compute the operands. 
314   // Note that we only count operands of type instruction and not other
315   // values such as branch labels for a branch or switch instruction.
316   //
317   // To do this efficiently, we'll walk all operands, build treeNodes
318   // for all instruction operands and save them in an array, and then
319   // insert children at the end if there are not more than 2.
320   // As a performance optimization, allocate a child array only
321   // if a fixed array is too small.
322   // 
323   int numChildren = 0;
324   const unsigned int MAX_CHILD = 8;
325   static InstrTreeNode* fixedChildArray[MAX_CHILD];
326   InstrTreeNode** childArray =
327     (instr->getNumOperands() > MAX_CHILD)
328     ? new (InstrTreeNode*)[instr->getNumOperands()]
329     : fixedChildArray;
330   
331   //
332   // Walk the operands of the instruction
333   // 
334   for (Instruction::op_iterator opIter = instr->op_begin();
335        opIter != instr->op_end();
336        ++opIter)
337     {
338       Value* operand = *opIter;
339       
340       // Check if the operand is a data value, not an branch label, type,
341       // method or module.  If the operand is an address type (i.e., label
342       // or method) that is used in an non-branching operation, e.g., `add'.
343       // that should be considered a data value.
344       
345       // Check latter condition here just to simplify the next IF.
346       bool includeAddressOperand =
347         ((operand->getValueType() == Value::BasicBlockVal
348           || operand->getValueType() == Value::MethodVal)
349          && ! instr->isTerminator());
350          
351       if (/* (*opIter) != NULL
352              &&*/ includeAddressOperand
353                   || operand->getValueType() == Value::InstructionVal
354                   ||  operand->getValueType() == Value::ConstantVal
355                   ||  operand->getValueType() == Value::MethodArgumentVal)
356         {// This operand is a data value
357           
358           // An instruction that computes the incoming value is added as a
359           // child of the current instruction if:
360           //   the value has only a single use
361           //   AND both instructions are in the same basic block
362           //   AND the instruction is not a PHI
363           // 
364           // (Note that if the value has only a single use (viz., `instr'),
365           //  the def of the value can be safely moved just before instr
366           //  and therefore it is safe to combine these two instructions.)
367           // 
368           // In all other cases, the virtual register holding the value
369           // is used directly, i.e., made a child of the instruction node.
370           // 
371           InstrTreeNode* opTreeNode;
372           if (operand->getValueType() == Value::InstructionVal
373               && operand->use_size() == 1
374               && ((Instruction*)operand)->getParent() == instr->getParent()
375               && ! ((Instruction*)operand)->isPHINode())
376             {
377               // Recursively create a treeNode for it.
378               opTreeNode =this->buildTreeForInstruction((Instruction*)operand);
379             }
380           else if (operand->getValueType() == Value::ConstantVal)
381             {
382               // Create a leaf node for a constant
383               opTreeNode = new ConstantNode((ConstPoolVal*) operand);
384             }
385           else
386             {
387               // Create a leaf node for the virtual register
388               opTreeNode = new VRegNode(operand);
389             }
390           
391           childArray[numChildren] = opTreeNode;
392           numChildren++;
393         }
394     }
395   
396   //-------------------------------------------------------------------- 
397   // Add any selected operands as children in the tree.
398   // Certain instructions can have more than 2 in some instances (viz.,
399   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
400   // array or struct). Make the operands of every such instruction into
401   // a right-leaning binary tree with the operand nodes at the leaves
402   // and VRegList nodes as internal nodes.
403   //-------------------------------------------------------------------- 
404   
405   InstrTreeNode* parent = treeNode;             // new VRegListNode();
406   int n;
407   
408   if (numChildren > 2)
409     {
410       unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
411       assert(instrOpcode == Instruction::Call ||
412              instrOpcode == Instruction::Load ||
413              instrOpcode == Instruction::Store ||
414              instrOpcode == Instruction::GetElementPtr);
415     }
416   
417   // Insert the first child as a direct child
418   if (numChildren >= 1)
419     this->setLeftChild(parent, childArray[0]);
420   
421   // Create a list node for children 2 .. N-1, if any
422   for (n = numChildren-1; n >= 2; n--)
423     { // We have more than two children
424       InstrTreeNode* listNode = new VRegListNode();
425       this->setRightChild(parent, listNode);
426       this->setLeftChild(listNode, childArray[numChildren - n]);
427       parent = listNode;
428     }
429   
430   // Now insert the last remaining child (if any).
431   if (numChildren >= 2)
432     {
433       assert(n == 1);
434       this->setRightChild(parent, childArray[numChildren - 1]);
435     }
436   
437   if (childArray != fixedChildArray)
438     {
439       delete[] childArray; 
440     }
441   
442   return treeNode;
443 }
444