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