fix spello
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a simple two pass scheduler.  The first pass attempts to push
11 // backward any lengthy instructions and critical paths.  The second pass packs
12 // instructions into semi-optimal time slots.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/CodeGen/ScheduleDAG.h"
17 #include "llvm/CodeGen/MachineConstantPool.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/SSARegMap.h"
20 #include "llvm/Target/TargetMachine.h"
21 #include "llvm/Target/TargetInstrInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Support/MathExtras.h"
24 using namespace llvm;
25
26
27 /// CountResults - The results of target nodes have register or immediate
28 /// operands first, then an optional chain, and optional flag operands (which do
29 /// not go into the machine instrs.)
30 static unsigned CountResults(SDNode *Node) {
31   unsigned N = Node->getNumValues();
32   while (N && Node->getValueType(N - 1) == MVT::Flag)
33     --N;
34   if (N && Node->getValueType(N - 1) == MVT::Other)
35     --N;    // Skip over chain result.
36   return N;
37 }
38
39 /// CountOperands  The inputs to target nodes have any actual inputs first,
40 /// followed by an optional chain operand, then flag operands.  Compute the
41 /// number of actual operands that  will go into the machine instr.
42 static unsigned CountOperands(SDNode *Node) {
43   unsigned N = Node->getNumOperands();
44   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
45     --N;
46   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
47     --N; // Ignore chain if it exists.
48   return N;
49 }
50
51 static unsigned CreateVirtualRegisters(MachineInstr *MI,
52                                        unsigned NumResults,
53                                        SSARegMap *RegMap,
54                                        const TargetInstrDescriptor &II) {
55   // Create the result registers for this node and add the result regs to
56   // the machine instruction.
57   const TargetOperandInfo *OpInfo = II.OpInfo;
58   unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
59   MI->addRegOperand(ResultReg, MachineOperand::Def);
60   for (unsigned i = 1; i != NumResults; ++i) {
61     assert(OpInfo[i].RegClass && "Isn't a register operand!");
62     MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
63                       MachineOperand::Def);
64   }
65   return ResultReg;
66 }
67
68 /// getVR - Return the virtual register corresponding to the specified result
69 /// of the specified node.
70 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
71   std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
72   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
73   return I->second + Op.ResNo;
74 }
75
76
77 /// AddOperand - Add the specified operand to the specified machine instr.  II
78 /// specifies the instruction information for the node, and IIOpNum is the
79 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
80 /// assertions only.
81 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
82                              unsigned IIOpNum,
83                              const TargetInstrDescriptor *II,
84                              std::map<SDNode*, unsigned> &VRBaseMap) {
85   if (Op.isTargetOpcode()) {
86     // Note that this case is redundant with the final else block, but we
87     // include it because it is the most common and it makes the logic
88     // simpler here.
89     assert(Op.getValueType() != MVT::Other &&
90            Op.getValueType() != MVT::Flag &&
91            "Chain and flag operands should occur at end of operand list!");
92     
93     // Get/emit the operand.
94     unsigned VReg = getVR(Op, VRBaseMap);
95     MI->addRegOperand(VReg, MachineOperand::Use);
96     
97     // Verify that it is right.
98     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
99     if (II) {
100       assert(II->OpInfo[IIOpNum].RegClass &&
101              "Don't have operand info for this instruction!");
102       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
103              "Register class of operand and regclass of use don't agree!");
104     }
105   } else if (ConstantSDNode *C =
106              dyn_cast<ConstantSDNode>(Op)) {
107     MI->addZeroExtImm64Operand(C->getValue());
108   } else if (RegisterSDNode*R =
109              dyn_cast<RegisterSDNode>(Op)) {
110     MI->addRegOperand(R->getReg(), MachineOperand::Use);
111   } else if (GlobalAddressSDNode *TGA =
112              dyn_cast<GlobalAddressSDNode>(Op)) {
113     MI->addGlobalAddressOperand(TGA->getGlobal(), false, TGA->getOffset());
114   } else if (BasicBlockSDNode *BB =
115              dyn_cast<BasicBlockSDNode>(Op)) {
116     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
117   } else if (FrameIndexSDNode *FI =
118              dyn_cast<FrameIndexSDNode>(Op)) {
119     MI->addFrameIndexOperand(FI->getIndex());
120   } else if (ConstantPoolSDNode *CP = 
121              dyn_cast<ConstantPoolSDNode>(Op)) {
122     int Offset = CP->getOffset();
123     unsigned Align = CP->getAlignment();
124     // MachineConstantPool wants an explicit alignment.
125     if (Align == 0) {
126       if (CP->get()->getType() == Type::DoubleTy)
127         Align = 3;  // always 8-byte align doubles.
128       else {
129         Align = TM.getTargetData()
130           .getTypeAlignmentShift(CP->get()->getType());
131         if (Align == 0) {
132           // Alignment of packed types.  FIXME!
133           Align = TM.getTargetData().getTypeSize(CP->get()->getType());
134           Align = Log2_64(Align);
135         }
136       }
137     }
138     
139     unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
140     MI->addConstantPoolIndexOperand(Idx, Offset);
141   } else if (ExternalSymbolSDNode *ES = 
142              dyn_cast<ExternalSymbolSDNode>(Op)) {
143     MI->addExternalSymbolOperand(ES->getSymbol(), false);
144   } else {
145     assert(Op.getValueType() != MVT::Other &&
146            Op.getValueType() != MVT::Flag &&
147            "Chain and flag operands should occur at end of operand list!");
148     unsigned VReg = getVR(Op, VRBaseMap);
149     MI->addRegOperand(VReg, MachineOperand::Use);
150     
151     // Verify that it is right.
152     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
153     if (II) {
154       assert(II->OpInfo[IIOpNum].RegClass &&
155              "Don't have operand info for this instruction!");
156       assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
157              "Register class of operand and regclass of use don't agree!");
158     }
159   }
160   
161 }
162
163
164 /// EmitNode - Generate machine code for an node and needed dependencies.
165 ///
166 void ScheduleDAG::EmitNode(SDNode *Node, 
167                            std::map<SDNode*, unsigned> &VRBaseMap) {
168   unsigned VRBase = 0;                 // First virtual register for node
169   
170   // If machine instruction
171   if (Node->isTargetOpcode()) {
172     unsigned Opc = Node->getTargetOpcode();
173     const TargetInstrDescriptor &II = TII->get(Opc);
174
175     unsigned NumResults = CountResults(Node);
176     unsigned NodeOperands = CountOperands(Node);
177     unsigned NumMIOperands = NodeOperands + NumResults;
178 #ifndef NDEBUG
179     assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
180            "#operands for dag node doesn't match .td file!"); 
181 #endif
182
183     // Create the new machine instruction.
184     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands, true, true);
185     
186     // Add result register values for things that are defined by this
187     // instruction.
188     
189     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
190     // the CopyToReg'd destination register instead of creating a new vreg.
191     if (NumResults == 1) {
192       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
193            UI != E; ++UI) {
194         SDNode *Use = *UI;
195         if (Use->getOpcode() == ISD::CopyToReg && 
196             Use->getOperand(2).Val == Node) {
197           unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
198           if (MRegisterInfo::isVirtualRegister(Reg)) {
199             VRBase = Reg;
200             MI->addRegOperand(Reg, MachineOperand::Def);
201             break;
202           }
203         }
204       }
205     }
206     
207     // Otherwise, create new virtual registers.
208     if (NumResults && VRBase == 0)
209       VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
210     
211     // Emit all of the actual operands of this instruction, adding them to the
212     // instruction as appropriate.
213     for (unsigned i = 0; i != NodeOperands; ++i)
214       AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
215     
216     // Now that we have emitted all operands, emit this instruction itself.
217     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
218       BB->insert(BB->end(), MI);
219     } else {
220       // Insert this instruction into the end of the basic block, potentially
221       // taking some custom action.
222       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
223     }
224   } else {
225     switch (Node->getOpcode()) {
226     default:
227       Node->dump(); 
228       assert(0 && "This target-independent node should have been selected!");
229     case ISD::EntryToken: // fall thru
230     case ISD::TokenFactor:
231       break;
232     case ISD::CopyToReg: {
233       unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
234       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
235       if (InReg != DestReg)   // Coalesced away the copy?
236         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
237                           RegMap->getRegClass(InReg));
238       break;
239     }
240     case ISD::CopyFromReg: {
241       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
242       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
243         VRBase = SrcReg;  // Just use the input register directly!
244         break;
245       }
246
247       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
248       // the CopyToReg'd destination register instead of creating a new vreg.
249       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
250            UI != E; ++UI) {
251         SDNode *Use = *UI;
252         if (Use->getOpcode() == ISD::CopyToReg && 
253             Use->getOperand(2).Val == Node) {
254           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
255           if (MRegisterInfo::isVirtualRegister(DestReg)) {
256             VRBase = DestReg;
257             break;
258           }
259         }
260       }
261
262       // Figure out the register class to create for the destreg.
263       const TargetRegisterClass *TRC = 0;
264       if (VRBase) {
265         TRC = RegMap->getRegClass(VRBase);
266       } else {
267
268         // Pick the register class of the right type that contains this physreg.
269         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
270              E = MRI->regclass_end(); I != E; ++I)
271           if ((*I)->hasType(Node->getValueType(0)) &&
272               (*I)->contains(SrcReg)) {
273             TRC = *I;
274             break;
275           }
276         assert(TRC && "Couldn't find register class for reg copy!");
277       
278         // Create the reg, emit the copy.
279         VRBase = RegMap->createVirtualRegister(TRC);
280       }
281       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
282       break;
283     }
284     case ISD::INLINEASM: {
285       unsigned NumOps = Node->getNumOperands();
286       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
287         --NumOps;  // Ignore the flag operand.
288       
289       // Create the inline asm machine instruction.
290       MachineInstr *MI =
291         new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
292
293       // Add the asm string as an external symbol operand.
294       const char *AsmStr =
295         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
296       MI->addExternalSymbolOperand(AsmStr, false);
297       
298       // Add all of the operand registers to the instruction.
299       for (unsigned i = 2; i != NumOps;) {
300         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
301         unsigned NumVals = Flags >> 3;
302         
303         MI->addZeroExtImm64Operand(Flags);
304         ++i;  // Skip the ID value.
305         
306         switch (Flags & 7) {
307         default: assert(0 && "Bad flags!");
308         case 1:  // Use of register.
309           for (; NumVals; --NumVals, ++i) {
310             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
311             MI->addMachineRegOperand(Reg, MachineOperand::Use);
312           }
313           break;
314         case 2:   // Def of register.
315           for (; NumVals; --NumVals, ++i) {
316             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
317             MI->addMachineRegOperand(Reg, MachineOperand::Def);
318           }
319           break;
320         case 3: { // Immediate.
321           assert(NumVals == 1 && "Unknown immediate value!");
322           uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
323           MI->addZeroExtImm64Operand(Val);
324           ++i;
325           break;
326         }
327         case 4:  // Addressing mode.
328           // The addressing mode has been selected, just add all of the
329           // operands to the machine instruction.
330           for (; NumVals; --NumVals, ++i)
331             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
332           break;
333         }
334       }
335       break;
336     }
337     }
338   }
339
340   assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
341   VRBaseMap[Node] = VRBase;
342 }
343
344 void ScheduleDAG::EmitNoop() {
345   TII->insertNoop(*BB, BB->end());
346 }
347
348 /// Run - perform scheduling.
349 ///
350 MachineBasicBlock *ScheduleDAG::Run() {
351   TII = TM.getInstrInfo();
352   MRI = TM.getRegisterInfo();
353   RegMap = BB->getParent()->getSSARegMap();
354   ConstPool = BB->getParent()->getConstantPool();
355
356   Schedule();
357   return BB;
358 }
359
360