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