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