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