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