Hide debugging options
[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 //---------------------------------------------------------------------------
21
22 #include "llvm/CodeGen/InstrForest.h"
23 #include "llvm/CodeGen/MachineCodeForInstruction.h"
24 #include "llvm/Function.h"
25 #include "llvm/iTerminators.h"
26 #include "llvm/iMemory.h"
27 #include "llvm/Constant.h"
28 #include "llvm/BasicBlock.h"
29 #include "llvm/Type.h"
30 #include "llvm/CodeGen/MachineInstr.h"
31 #include "Support/STLExtras.h"
32 #include <alloca.h>
33 #include <iostream>
34 using std::cerr;
35 using std::vector;
36
37 //------------------------------------------------------------------------ 
38 // class InstrTreeNode
39 //------------------------------------------------------------------------ 
40
41 void
42 InstrTreeNode::dump(int dumpChildren, int indent) const
43 {
44   dumpNode(indent);
45   
46   if (dumpChildren)
47     {
48       if (LeftChild)
49         LeftChild->dump(dumpChildren, indent+1);
50       if (RightChild)
51         RightChild->dump(dumpChildren, indent+1);
52     }
53 }
54
55
56 InstructionNode::InstructionNode(Instruction* I)
57   : InstrTreeNode(NTInstructionNode, I),
58     codeIsFoldedIntoParent(false)
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   const MachineCodeForInstruction &mvec =
129     MachineCodeForInstruction::get(getInstruction());
130
131   if (mvec.size() > 0)
132     cerr << "\tMachine Instructions:  ";
133
134   for (unsigned int i=0; i < mvec.size(); ++i) {
135     mvec[i]->dump(0);
136     if (i < mvec.size() - 1)
137       cerr << ";  ";
138   }
139   
140   cerr << "\n";
141 }
142
143
144 void
145 VRegListNode::dumpNode(int indent) const
146 {
147   for (int i=0; i < indent; i++)
148     cerr << "    ";
149   
150   cerr << "List" << "\n";
151 }
152
153
154 void
155 VRegNode::dumpNode(int indent) const
156 {
157   for (int i=0; i < indent; i++)
158     cerr << "    ";
159   
160   cerr << "VReg " << getValue() << "\t(type "
161        << (int) getValue()->getValueType() << ")" << "\n";
162 }
163
164 void
165 ConstantNode::dumpNode(int indent) const
166 {
167   for (int i=0; i < indent; i++)
168     cerr << "    ";
169   
170   cerr << "Constant " << getValue() << "\t(type "
171        << (int) getValue()->getValueType() << ")" << "\n";
172 }
173
174 void
175 LabelNode::dumpNode(int indent) const
176 {
177   for (int i=0; i < indent; i++)
178     cerr << "    ";
179   
180   cerr << "Label " << getValue() << "\n";
181 }
182
183 //------------------------------------------------------------------------
184 // class InstrForest
185 // 
186 // A forest of instruction trees, usually for a single method.
187 //------------------------------------------------------------------------ 
188
189 InstrForest::InstrForest(Function *F)
190 {
191   for (Function::iterator FI = F->begin(), FE = F->end(); FI != FE; ++FI) {
192     BasicBlock *BB = *FI;
193     for_each(BB->begin(), BB->end(),
194              bind_obj(this, &InstrForest::buildTreeForInstruction));
195   }
196 }
197
198 InstrForest::~InstrForest()
199 {
200   for_each(treeRoots.begin(), treeRoots.end(), deleter<InstructionNode>);
201 }
202
203 void
204 InstrForest::dump() const
205 {
206   for (const_root_iterator I = roots_begin(); I != roots_end(); ++I)
207     (*I)->dump(/*dumpChildren*/ 1, /*indent*/ 0);
208 }
209
210 inline void
211 InstrForest::eraseRoot(InstructionNode* node)
212 {
213   for (RootSet::reverse_iterator RI=treeRoots.rbegin(), RE=treeRoots.rend();
214        RI != RE; ++RI)
215     if (*RI == node)
216       treeRoots.erase(RI.base()-1);
217 }
218
219 inline void
220 InstrForest::noteTreeNodeForInstr(Instruction *instr,
221                                   InstructionNode *treeNode)
222 {
223   assert(treeNode->getNodeType() == InstrTreeNode::NTInstructionNode);
224   (*this)[instr] = treeNode;
225   treeRoots.push_back(treeNode);        // mark node as root of a new tree
226 }
227
228
229 inline void
230 InstrForest::setLeftChild(InstrTreeNode *parent, InstrTreeNode *child)
231 {
232   parent->LeftChild = child;
233   child->Parent = parent;
234   if (child->getNodeType() == InstrTreeNode::NTInstructionNode)
235     eraseRoot((InstructionNode*) child); // no longer a tree root
236 }
237
238 inline void
239 InstrForest::setRightChild(InstrTreeNode *parent, InstrTreeNode *child)
240 {
241   parent->RightChild = child;
242   child->Parent = parent;
243   if (child->getNodeType() == InstrTreeNode::NTInstructionNode)
244     eraseRoot((InstructionNode*) child); // no longer a tree root
245 }
246
247
248 InstructionNode*
249 InstrForest::buildTreeForInstruction(Instruction *instr)
250 {
251   InstructionNode *treeNode = getTreeNodeForInstr(instr);
252   if (treeNode)
253     {
254       // treeNode has already been constructed for this instruction
255       assert(treeNode->getInstruction() == instr);
256       return treeNode;
257     }
258   
259   // Otherwise, create a new tree node for this instruction.
260   // 
261   treeNode = new InstructionNode(instr);
262   noteTreeNodeForInstr(instr, treeNode);
263   
264   if (instr->getOpcode() == Instruction::Call)
265     { // Operands of call instruction
266       return treeNode;
267     }
268   
269   // If the instruction has more than 2 instruction operands,
270   // then we need to create artificial list nodes to hold them.
271   // (Note that we only count operands that get tree nodes, and not
272   // others such as branch labels for a branch or switch instruction.)
273   //
274   // To do this efficiently, we'll walk all operands, build treeNodes
275   // for all appropriate operands and save them in an array.  We then
276   // insert children at the end, creating list nodes where needed.
277   // As a performance optimization, allocate a child array only
278   // if a fixed array is too small.
279   // 
280   int numChildren = 0;
281   InstrTreeNode **childArray =
282     (InstrTreeNode **)alloca(instr->getNumOperands()*sizeof(InstrTreeNode *));
283   
284   //
285   // Walk the operands of the instruction
286   // 
287   for (Instruction::op_iterator O = instr->op_begin(); O!=instr->op_end(); ++O)
288     {
289       Value* operand = *O;
290       
291       // Check if the operand is a data value, not an branch label, type,
292       // method or module.  If the operand is an address type (i.e., label
293       // or method) that is used in an non-branching operation, e.g., `add'.
294       // that should be considered a data value.
295     
296       // Check latter condition here just to simplify the next IF.
297       bool includeAddressOperand =
298         (isa<BasicBlock>(operand) || isa<Function>(operand))
299         && !instr->isTerminator();
300     
301       if (includeAddressOperand || isa<Instruction>(operand) ||
302           isa<Constant>(operand) || isa<Argument>(operand) ||
303           isa<GlobalVariable>(operand))
304         {
305           // This operand is a data value
306         
307           // An instruction that computes the incoming value is added as a
308           // child of the current instruction if:
309           //   the value has only a single use
310           //   AND both instructions are in the same basic block.
311           //   AND the current instruction is not a PHI (because the incoming
312           //            value is conceptually in a predecessor block,
313           //            even though it may be in the same static block)
314           // 
315           // (Note that if the value has only a single use (viz., `instr'),
316           //  the def of the value can be safely moved just before instr
317           //  and therefore it is safe to combine these two instructions.)
318           // 
319           // In all other cases, the virtual register holding the value
320           // is used directly, i.e., made a child of the instruction node.
321           // 
322           InstrTreeNode* opTreeNode;
323           if (isa<Instruction>(operand) && operand->use_size() == 1 &&
324               cast<Instruction>(operand)->getParent() == instr->getParent() &&
325               instr->getOpcode() != Instruction::PHINode &&
326               instr->getOpcode() != Instruction::Call)
327             {
328               // Recursively create a treeNode for it.
329               opTreeNode = buildTreeForInstruction((Instruction*)operand);
330             }
331           else if (Constant *CPV = dyn_cast<Constant>(operand))
332             {
333               // Create a leaf node for a constant
334               opTreeNode = new ConstantNode(CPV);
335             }
336           else
337             {
338               // Create a leaf node for the virtual register
339               opTreeNode = new VRegNode(operand);
340             }
341
342           childArray[numChildren++] = opTreeNode;
343         }
344     }
345   
346   //-------------------------------------------------------------------- 
347   // Add any selected operands as children in the tree.
348   // Certain instructions can have more than 2 in some instances (viz.,
349   // a CALL or a memory access -- LOAD, STORE, and GetElemPtr -- to an
350   // array or struct). Make the operands of every such instruction into
351   // a right-leaning binary tree with the operand nodes at the leaves
352   // and VRegList nodes as internal nodes.
353   //-------------------------------------------------------------------- 
354   
355   InstrTreeNode *parent = treeNode;
356   
357   if (numChildren > 2)
358     {
359       unsigned instrOpcode = treeNode->getInstruction()->getOpcode();
360       assert(instrOpcode == Instruction::PHINode ||
361              instrOpcode == Instruction::Call ||
362              instrOpcode == Instruction::Load ||
363              instrOpcode == Instruction::Store ||
364              instrOpcode == Instruction::GetElementPtr);
365     }
366   
367   // Insert the first child as a direct child
368   if (numChildren >= 1)
369     setLeftChild(parent, childArray[0]);
370
371   int n;
372   
373   // Create a list node for children 2 .. N-1, if any
374   for (n = numChildren-1; n >= 2; n--)
375     {
376       // We have more than two children
377       InstrTreeNode *listNode = new VRegListNode();
378       setRightChild(parent, listNode);
379       setLeftChild(listNode, childArray[numChildren - n]);
380       parent = listNode;
381     }
382   
383   // Now insert the last remaining child (if any).
384   if (numChildren >= 2)
385     {
386       assert(n == 1);
387       setRightChild(parent, childArray[numChildren - 1]);
388     }
389   
390   return treeNode;
391 }