e7980156905ac2577202f57ef71b6b245034184e
[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 is distributed under the University of Illinois Open Source
6 // 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 #define DEBUG_TYPE "pre-RA-sched"
17 #include "llvm/Constants.h"
18 #include "llvm/Type.h"
19 #include "llvm/CodeGen/ScheduleDAG.h"
20 #include "llvm/CodeGen/MachineConstantPool.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Target/TargetData.h"
24 #include "llvm/Target/TargetMachine.h"
25 #include "llvm/Target/TargetInstrInfo.h"
26 #include "llvm/Target/TargetLowering.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 using namespace llvm;
30
31 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
32                          const TargetMachine &tm)
33   : DAG(dag), BB(bb), TM(tm), RegInfo(BB->getParent()->getRegInfo()) {
34     TII = TM.getInstrInfo();
35     MF  = &DAG.getMachineFunction();
36     TRI = TM.getRegisterInfo();
37     ConstPool = BB->getParent()->getConstantPool();
38 }
39
40 /// CheckForPhysRegDependency - Check if the dependency between def and use of
41 /// a specified operand is a physical register dependency. If so, returns the
42 /// register and the cost of copying the register.
43 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
44                                       const TargetRegisterInfo *TRI, 
45                                       const TargetInstrInfo *TII,
46                                       unsigned &PhysReg, int &Cost) {
47   if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
48     return;
49
50   unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
51   if (TargetRegisterInfo::isVirtualRegister(Reg))
52     return;
53
54   unsigned ResNo = Use->getOperand(2).ResNo;
55   if (Def->isTargetOpcode()) {
56     const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
57     if (ResNo >= II.getNumDefs() &&
58         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
59       PhysReg = Reg;
60       const TargetRegisterClass *RC =
61         TRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
62       Cost = RC->getCopyCost();
63     }
64   }
65 }
66
67 SUnit *ScheduleDAG::Clone(SUnit *Old) {
68   SUnit *SU = NewSUnit(Old->Node);
69   for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
70     SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
71   SU->InstanceNo = SUnitMap[Old->Node].size();
72   SU->Latency = Old->Latency;
73   SU->isTwoAddress = Old->isTwoAddress;
74   SU->isCommutable = Old->isCommutable;
75   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
76   SUnitMap[Old->Node].push_back(SU);
77   return SU;
78 }
79
80
81 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
82 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
83 /// together nodes with a single SUnit.
84 void ScheduleDAG::BuildSchedUnits() {
85   // Reserve entries in the vector for each of the SUnits we are creating.  This
86   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
87   // invalidated.
88   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
89   
90   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
91        E = DAG.allnodes_end(); NI != E; ++NI) {
92     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
93       continue;
94     
95     // If this node has already been processed, stop now.
96     if (SUnitMap[NI].size()) continue;
97     
98     SUnit *NodeSUnit = NewSUnit(NI);
99     
100     // See if anything is flagged to this node, if so, add them to flagged
101     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
102     // are required the be the last operand and result of a node.
103     
104     // Scan up, adding flagged preds to FlaggedNodes.
105     SDNode *N = NI;
106     if (N->getNumOperands() &&
107         N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
108       do {
109         N = N->getOperand(N->getNumOperands()-1).Val;
110         NodeSUnit->FlaggedNodes.push_back(N);
111         SUnitMap[N].push_back(NodeSUnit);
112       } while (N->getNumOperands() &&
113                N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
114       std::reverse(NodeSUnit->FlaggedNodes.begin(),
115                    NodeSUnit->FlaggedNodes.end());
116     }
117     
118     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
119     // have a user of the flag operand.
120     N = NI;
121     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
122       SDOperand FlagVal(N, N->getNumValues()-1);
123       
124       // There are either zero or one users of the Flag result.
125       bool HasFlagUse = false;
126       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
127            UI != E; ++UI)
128         if (FlagVal.isOperand(*UI)) {
129           HasFlagUse = true;
130           NodeSUnit->FlaggedNodes.push_back(N);
131           SUnitMap[N].push_back(NodeSUnit);
132           N = *UI;
133           break;
134         }
135       if (!HasFlagUse) break;
136     }
137     
138     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
139     // Update the SUnit
140     NodeSUnit->Node = N;
141     SUnitMap[N].push_back(NodeSUnit);
142
143     ComputeLatency(NodeSUnit);
144   }
145   
146   // Pass 2: add the preds, succs, etc.
147   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
148     SUnit *SU = &SUnits[su];
149     SDNode *MainNode = SU->Node;
150     
151     if (MainNode->isTargetOpcode()) {
152       unsigned Opc = MainNode->getTargetOpcode();
153       const TargetInstrDesc &TID = TII->get(Opc);
154       for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
155         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
156           SU->isTwoAddress = true;
157           break;
158         }
159       }
160       if (TID.isCommutable())
161         SU->isCommutable = true;
162     }
163     
164     // Find all predecessors and successors of the group.
165     // Temporarily add N to make code simpler.
166     SU->FlaggedNodes.push_back(MainNode);
167     
168     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
169       SDNode *N = SU->FlaggedNodes[n];
170       if (N->isTargetOpcode() &&
171           TII->get(N->getTargetOpcode()).getImplicitDefs() &&
172           CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
173         SU->hasPhysRegDefs = true;
174       
175       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
176         SDNode *OpN = N->getOperand(i).Val;
177         if (isPassiveNode(OpN)) continue;   // Not scheduled.
178         SUnit *OpSU = SUnitMap[OpN].front();
179         assert(OpSU && "Node has no SUnit!");
180         if (OpSU == SU) continue;           // In the same group.
181
182         MVT::ValueType OpVT = N->getOperand(i).getValueType();
183         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
184         bool isChain = OpVT == MVT::Other;
185
186         unsigned PhysReg = 0;
187         int Cost = 1;
188         // Determine if this is a physical register dependency.
189         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
190         SU->addPred(OpSU, isChain, false, PhysReg, Cost);
191       }
192     }
193     
194     // Remove MainNode from FlaggedNodes again.
195     SU->FlaggedNodes.pop_back();
196   }
197   
198   return;
199 }
200
201 void ScheduleDAG::ComputeLatency(SUnit *SU) {
202   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
203   
204   // Compute the latency for the node.  We use the sum of the latencies for
205   // all nodes flagged together into this SUnit.
206   if (InstrItins.isEmpty()) {
207     // No latency information.
208     SU->Latency = 1;
209   } else {
210     SU->Latency = 0;
211     if (SU->Node->isTargetOpcode()) {
212       unsigned SchedClass =
213         TII->get(SU->Node->getTargetOpcode()).getSchedClass();
214       InstrStage *S = InstrItins.begin(SchedClass);
215       InstrStage *E = InstrItins.end(SchedClass);
216       for (; S != E; ++S)
217         SU->Latency += S->Cycles;
218     }
219     for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
220       SDNode *FNode = SU->FlaggedNodes[i];
221       if (FNode->isTargetOpcode()) {
222         unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
223         InstrStage *S = InstrItins.begin(SchedClass);
224         InstrStage *E = InstrItins.end(SchedClass);
225         for (; S != E; ++S)
226           SU->Latency += S->Cycles;
227       }
228     }
229   }
230 }
231
232 void ScheduleDAG::CalculateDepths() {
233   std::vector<std::pair<SUnit*, unsigned> > WorkList;
234   for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
235     if (SUnits[i].Preds.empty())
236       WorkList.push_back(std::make_pair(&SUnits[i], 0U));
237
238   while (!WorkList.empty()) {
239     SUnit *SU = WorkList.back().first;
240     unsigned Depth = WorkList.back().second;
241     WorkList.pop_back();
242     if (SU->Depth == 0 || Depth > SU->Depth) {
243       SU->Depth = Depth;
244       for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
245            I != E; ++I)
246         WorkList.push_back(std::make_pair(I->Dep, Depth+1));
247     }
248   }
249 }
250
251 void ScheduleDAG::CalculateHeights() {
252   std::vector<std::pair<SUnit*, unsigned> > WorkList;
253   SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
254   WorkList.push_back(std::make_pair(Root, 0U));
255
256   while (!WorkList.empty()) {
257     SUnit *SU = WorkList.back().first;
258     unsigned Height = WorkList.back().second;
259     WorkList.pop_back();
260     if (SU->Height == 0 || Height > SU->Height) {
261       SU->Height = Height;
262       for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
263            I != E; ++I)
264         WorkList.push_back(std::make_pair(I->Dep, Height+1));
265     }
266   }
267 }
268
269 /// CountResults - The results of target nodes have register or immediate
270 /// operands first, then an optional chain, and optional flag operands (which do
271 /// not go into the resulting MachineInstr).
272 unsigned ScheduleDAG::CountResults(SDNode *Node) {
273   unsigned N = Node->getNumValues();
274   while (N && Node->getValueType(N - 1) == MVT::Flag)
275     --N;
276   if (N && Node->getValueType(N - 1) == MVT::Other)
277     --N;    // Skip over chain result.
278   return N;
279 }
280
281 /// CountOperands - The inputs to target nodes have any actual inputs first,
282 /// followed by optional memory operands chain operand, then flag operands.
283 /// Compute the number of actual operands that will go into the resulting
284 /// MachineInstr.
285 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
286   unsigned N = Node->getNumOperands();
287   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
288     --N;
289   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
290     --N; // Ignore chain if it exists.
291   while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
292     --N; // Ignore MemOperand nodes
293   return N;
294 }
295
296 /// CountMemOperands - Find the index of the last MemOperandSDNode operand
297 unsigned ScheduleDAG::CountMemOperands(SDNode *Node) {
298   unsigned N = Node->getNumOperands();
299   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
300     --N;
301   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
302     --N; // Ignore chain if it exists.
303   return N;
304 }
305
306 static const TargetRegisterClass *getInstrOperandRegClass(
307         const TargetRegisterInfo *TRI, 
308         const TargetInstrInfo *TII,
309         const TargetInstrDesc &II,
310         unsigned Op) {
311   if (Op >= II.getNumOperands()) {
312     assert(II.isVariadic() && "Invalid operand # of instruction");
313     return NULL;
314   }
315   if (II.OpInfo[Op].isLookupPtrRegClass())
316     return TII->getPointerRegClass();
317   return TRI->getRegClass(II.OpInfo[Op].RegClass);
318 }
319
320 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
321                                   unsigned InstanceNo, unsigned SrcReg,
322                                   DenseMap<SDOperand, unsigned> &VRBaseMap) {
323   unsigned VRBase = 0;
324   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
325     // Just use the input register directly!
326     if (InstanceNo > 0)
327       VRBaseMap.erase(SDOperand(Node, ResNo));
328     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
329     assert(isNew && "Node emitted out of order - early");
330     return;
331   }
332
333   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
334   // the CopyToReg'd destination register instead of creating a new vreg.
335   bool MatchReg = true;
336   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
337        UI != E; ++UI) {
338     SDNode *Use = *UI;
339     bool Match = true;
340     if (Use->getOpcode() == ISD::CopyToReg && 
341         Use->getOperand(2).Val == Node &&
342         Use->getOperand(2).ResNo == ResNo) {
343       unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
344       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
345         VRBase = DestReg;
346         Match = false;
347       } else if (DestReg != SrcReg)
348         Match = false;
349     } else {
350       for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
351         SDOperand Op = Use->getOperand(i);
352         if (Op.Val != Node || Op.ResNo != ResNo)
353           continue;
354         MVT::ValueType VT = Node->getValueType(Op.ResNo);
355         if (VT != MVT::Other && VT != MVT::Flag)
356           Match = false;
357       }
358     }
359     MatchReg &= Match;
360     if (VRBase)
361       break;
362   }
363
364   const TargetRegisterClass *TRC = 0;
365   // Figure out the register class to create for the destreg.
366   if (VRBase)
367     TRC = RegInfo.getRegClass(VRBase);
368   else
369     TRC = TRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
370     
371   // If all uses are reading from the src physical register and copying the
372   // register is either impossible or very expensive, then don't create a copy.
373   if (MatchReg && TRC->getCopyCost() < 0) {
374     VRBase = SrcReg;
375   } else {
376     // Create the reg, emit the copy.
377     VRBase = RegInfo.createVirtualRegister(TRC);
378     TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
379   }
380
381   if (InstanceNo > 0)
382     VRBaseMap.erase(SDOperand(Node, ResNo));
383   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
384   assert(isNew && "Node emitted out of order - early");
385 }
386
387 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
388                                          MachineInstr *MI,
389                                          const TargetInstrDesc &II,
390                                      DenseMap<SDOperand, unsigned> &VRBaseMap) {
391   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
392     // If the specific node value is only used by a CopyToReg and the dest reg
393     // is a vreg, use the CopyToReg'd destination register instead of creating
394     // a new vreg.
395     unsigned VRBase = 0;
396     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
397          UI != E; ++UI) {
398       SDNode *Use = *UI;
399       if (Use->getOpcode() == ISD::CopyToReg && 
400           Use->getOperand(2).Val == Node &&
401           Use->getOperand(2).ResNo == i) {
402         unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
403         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
404           VRBase = Reg;
405           MI->addOperand(MachineOperand::CreateReg(Reg, true));
406           break;
407         }
408       }
409     }
410
411     // Create the result registers for this node and add the result regs to
412     // the machine instruction.
413     if (VRBase == 0) {
414       const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
415       assert(RC && "Isn't a register operand!");
416       VRBase = RegInfo.createVirtualRegister(RC);
417       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
418     }
419
420     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
421     assert(isNew && "Node emitted out of order - early");
422   }
423 }
424
425 /// getVR - Return the virtual register corresponding to the specified result
426 /// of the specified node.
427 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
428   DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
429   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
430   return I->second;
431 }
432
433
434 /// AddOperand - Add the specified operand to the specified machine instr.  II
435 /// specifies the instruction information for the node, and IIOpNum is the
436 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
437 /// assertions only.
438 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
439                              unsigned IIOpNum,
440                              const TargetInstrDesc *II,
441                              DenseMap<SDOperand, unsigned> &VRBaseMap) {
442   if (Op.isTargetOpcode()) {
443     // Note that this case is redundant with the final else block, but we
444     // include it because it is the most common and it makes the logic
445     // simpler here.
446     assert(Op.getValueType() != MVT::Other &&
447            Op.getValueType() != MVT::Flag &&
448            "Chain and flag operands should occur at end of operand list!");
449     
450     // Get/emit the operand.
451     unsigned VReg = getVR(Op, VRBaseMap);
452     const TargetInstrDesc &TID = MI->getDesc();
453     bool isOptDef = (IIOpNum < TID.getNumOperands())
454       ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
455     MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
456     
457     // Verify that it is right.
458     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
459     if (II) {
460       const TargetRegisterClass *RC =
461                           getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
462       assert(RC && "Don't have operand info for this instruction!");
463       const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
464       if (VRC != RC) {
465         cerr << "Register class of operand and regclass of use don't agree!\n";
466 #ifndef NDEBUG
467         cerr << "Operand = " << IIOpNum << "\n";
468         cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
469         cerr << "MI = "; MI->print(cerr);
470         cerr << "VReg = " << VReg << "\n";
471         cerr << "VReg RegClass     size = " << VRC->getSize()
472              << ", align = " << VRC->getAlignment() << "\n";
473         cerr << "Expected RegClass size = " << RC->getSize()
474              << ", align = " << RC->getAlignment() << "\n";
475 #endif
476         cerr << "Fatal error, aborting.\n";
477         abort();
478       }
479     }
480   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
481     MI->addOperand(MachineOperand::CreateImm(C->getValue()));
482   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
483     const Type *FType = MVT::getTypeForValueType(Op.getValueType());
484     ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
485     MI->addOperand(MachineOperand::CreateFPImm(CFP));
486   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
487     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
488   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
489     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
490   } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
491     MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
492   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
493     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
494   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
495     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
496   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
497     int Offset = CP->getOffset();
498     unsigned Align = CP->getAlignment();
499     const Type *Type = CP->getType();
500     // MachineConstantPool wants an explicit alignment.
501     if (Align == 0) {
502       Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
503       if (Align == 0) {
504         // Alignment of vector types.  FIXME!
505         Align = TM.getTargetData()->getABITypeSize(Type);
506         Align = Log2_64(Align);
507       }
508     }
509     
510     unsigned Idx;
511     if (CP->isMachineConstantPoolEntry())
512       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
513     else
514       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
515     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
516   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
517     MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
518   } else {
519     assert(Op.getValueType() != MVT::Other &&
520            Op.getValueType() != MVT::Flag &&
521            "Chain and flag operands should occur at end of operand list!");
522     unsigned VReg = getVR(Op, VRBaseMap);
523     MI->addOperand(MachineOperand::CreateReg(VReg, false));
524     
525     // Verify that it is right.
526     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
527     if (II) {
528       const TargetRegisterClass *RC =
529                             getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
530       assert(RC && "Don't have operand info for this instruction!");
531       assert(RegInfo.getRegClass(VReg) == RC &&
532              "Register class of operand and regclass of use don't agree!");
533     }
534   }
535   
536 }
537
538 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
539   MI->addMemOperand(MO);
540 }
541
542 // Returns the Register Class of a subregister
543 static const TargetRegisterClass *getSubRegisterRegClass(
544         const TargetRegisterClass *TRC,
545         unsigned SubIdx) {
546   // Pick the register class of the subregister
547   TargetRegisterInfo::regclass_iterator I =
548     TRC->subregclasses_begin() + SubIdx-1;
549   assert(I < TRC->subregclasses_end() && 
550          "Invalid subregister index for register class");
551   return *I;
552 }
553
554 static const TargetRegisterClass *getSuperregRegisterClass(
555         const TargetRegisterClass *TRC,
556         unsigned SubIdx,
557         MVT::ValueType VT) {
558   // Pick the register class of the superegister for this type
559   for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
560          E = TRC->superregclasses_end(); I != E; ++I)
561     if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
562       return *I;
563   assert(false && "Couldn't find the register class");
564   return 0;
565 }
566
567 /// EmitSubregNode - Generate machine code for subreg nodes.
568 ///
569 void ScheduleDAG::EmitSubregNode(SDNode *Node, 
570                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
571   unsigned VRBase = 0;
572   unsigned Opc = Node->getTargetOpcode();
573   if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
574     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
575     // the CopyToReg'd destination register instead of creating a new vreg.
576     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
577          UI != E; ++UI) {
578       SDNode *Use = *UI;
579       if (Use->getOpcode() == ISD::CopyToReg && 
580           Use->getOperand(2).Val == Node) {
581         unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
582         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
583           VRBase = DestReg;
584           break;
585         }
586       }
587     }
588     
589     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
590     
591     // TODO: If the node is a use of a CopyFromReg from a physical register
592     // fold the extract into the copy now
593
594     // Create the extract_subreg machine instruction.
595     MachineInstr *MI =
596       new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
597
598     // Figure out the register class to create for the destreg.
599     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
600     const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
601     const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
602
603     if (VRBase) {
604       // Grab the destination register
605       const TargetRegisterClass *DRC = 0;
606       DRC = RegInfo.getRegClass(VRBase);
607       assert(SRC && DRC && SRC == DRC && 
608              "Source subregister and destination must have the same class");
609     } else {
610       // Create the reg
611       assert(SRC && "Couldn't find source register class");
612       VRBase = RegInfo.createVirtualRegister(SRC);
613     }
614     
615     // Add def, source, and subreg index
616     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
617     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
618     MI->addOperand(MachineOperand::CreateImm(SubIdx));
619     
620   } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
621     assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
622             "Malformed insert_subreg node");
623     bool isUndefInput = (Node->getNumOperands() == 2);
624     unsigned SubReg = 0;
625     unsigned SubIdx = 0;
626     
627     if (isUndefInput) {
628       SubReg = getVR(Node->getOperand(0), VRBaseMap);
629       SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
630     } else {
631       SubReg = getVR(Node->getOperand(1), VRBaseMap);
632       SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
633     }
634     
635     // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
636     // to allow coalescing in the allocator
637           
638     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
639     // the CopyToReg'd destination register instead of creating a new vreg.
640     // If the CopyToReg'd destination register is physical, then fold the
641     // insert into the copy
642     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
643          UI != E; ++UI) {
644       SDNode *Use = *UI;
645       if (Use->getOpcode() == ISD::CopyToReg && 
646           Use->getOperand(2).Val == Node) {
647         unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
648         if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
649           VRBase = DestReg;
650           break;
651         }
652       }
653     }
654     
655     // Create the insert_subreg machine instruction.
656     MachineInstr *MI =
657       new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
658       
659     // Figure out the register class to create for the destreg.
660     const TargetRegisterClass *TRC = 0;
661     if (VRBase) {
662       TRC = RegInfo.getRegClass(VRBase);
663     } else {
664       TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx, 
665                                      Node->getValueType(0));
666       assert(TRC && "Couldn't determine register class for insert_subreg");
667       VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
668     }
669     
670     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
671     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
672     if (!isUndefInput)
673       AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
674     MI->addOperand(MachineOperand::CreateImm(SubIdx));
675   } else
676     assert(0 && "Node is not a subreg insert or extract");
677      
678   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
679   assert(isNew && "Node emitted out of order - early");
680 }
681
682 /// EmitNode - Generate machine code for an node and needed dependencies.
683 ///
684 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
685                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
686   // If machine instruction
687   if (Node->isTargetOpcode()) {
688     unsigned Opc = Node->getTargetOpcode();
689     
690     // Handle subreg insert/extract specially
691     if (Opc == TargetInstrInfo::EXTRACT_SUBREG || 
692         Opc == TargetInstrInfo::INSERT_SUBREG) {
693       EmitSubregNode(Node, VRBaseMap);
694       return;
695     }
696     
697     const TargetInstrDesc &II = TII->get(Opc);
698
699     unsigned NumResults = CountResults(Node);
700     unsigned NodeOperands = CountOperands(Node);
701     unsigned NodeMemOperands = CountMemOperands(Node);
702     unsigned NumMIOperands = NodeOperands + NumResults;
703     bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
704                           II.getImplicitDefs() != 0;
705 #ifndef NDEBUG
706     assert((II.getNumOperands() == NumMIOperands ||
707             HasPhysRegOuts || II.isVariadic()) &&
708            "#operands for dag node doesn't match .td file!"); 
709 #endif
710
711     // Create the new machine instruction.
712     MachineInstr *MI = new MachineInstr(II);
713     
714     // Add result register values for things that are defined by this
715     // instruction.
716     if (NumResults)
717       CreateVirtualRegisters(Node, MI, II, VRBaseMap);
718     
719     // Emit all of the actual operands of this instruction, adding them to the
720     // instruction as appropriate.
721     for (unsigned i = 0; i != NodeOperands; ++i)
722       AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
723
724     // Emit all of the memory operands of this instruction
725     for (unsigned i = NodeOperands; i != NodeMemOperands; ++i)
726       AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
727
728     // Commute node if it has been determined to be profitable.
729     if (CommuteSet.count(Node)) {
730       MachineInstr *NewMI = TII->commuteInstruction(MI);
731       if (NewMI == 0)
732         DOUT << "Sched: COMMUTING FAILED!\n";
733       else {
734         DOUT << "Sched: COMMUTED TO: " << *NewMI;
735         if (MI != NewMI) {
736           delete MI;
737           MI = NewMI;
738         }
739       }
740     }
741
742     if (II.usesCustomDAGSchedInsertionHook())
743       // Insert this instruction into the basic block using a target
744       // specific inserter which may returns a new basic block.
745       BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
746     else
747       BB->push_back(MI);
748
749     // Additional results must be an physical register def.
750     if (HasPhysRegOuts) {
751       for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
752         unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
753         if (Node->hasAnyUseOfValue(i))
754           EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
755       }
756     }
757   } else {
758     switch (Node->getOpcode()) {
759     default:
760 #ifndef NDEBUG
761       Node->dump(&DAG);
762 #endif
763       assert(0 && "This target-independent node should have been selected!");
764     case ISD::EntryToken: // fall thru
765     case ISD::TokenFactor:
766     case ISD::LABEL:
767     case ISD::DECLARE:
768     case ISD::SRCVALUE:
769       break;
770     case ISD::CopyToReg: {
771       unsigned InReg;
772       if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
773         InReg = R->getReg();
774       else
775         InReg = getVR(Node->getOperand(2), VRBaseMap);
776       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
777       if (InReg != DestReg)  {// Coalesced away the copy?
778         const TargetRegisterClass *TRC = 0;
779         // Get the target register class
780         if (TargetRegisterInfo::isVirtualRegister(InReg))
781           TRC = RegInfo.getRegClass(InReg);
782         else
783           TRC =
784             TRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
785                                             InReg);
786         TII->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
787       }
788       break;
789     }
790     case ISD::CopyFromReg: {
791       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
792       EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
793       break;
794     }
795     case ISD::INLINEASM: {
796       unsigned NumOps = Node->getNumOperands();
797       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
798         --NumOps;  // Ignore the flag operand.
799       
800       // Create the inline asm machine instruction.
801       MachineInstr *MI =
802         new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
803
804       // Add the asm string as an external symbol operand.
805       const char *AsmStr =
806         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
807       MI->addOperand(MachineOperand::CreateES(AsmStr));
808       
809       // Add all of the operand registers to the instruction.
810       for (unsigned i = 2; i != NumOps;) {
811         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
812         unsigned NumVals = Flags >> 3;
813         
814         MI->addOperand(MachineOperand::CreateImm(Flags));
815         ++i;  // Skip the ID value.
816         
817         switch (Flags & 7) {
818         default: assert(0 && "Bad flags!");
819         case 1:  // Use of register.
820           for (; NumVals; --NumVals, ++i) {
821             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
822             MI->addOperand(MachineOperand::CreateReg(Reg, false));
823           }
824           break;
825         case 2:   // Def of register.
826           for (; NumVals; --NumVals, ++i) {
827             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
828             MI->addOperand(MachineOperand::CreateReg(Reg, true));
829           }
830           break;
831         case 3: { // Immediate.
832           for (; NumVals; --NumVals, ++i) {
833             if (ConstantSDNode *CS =
834                    dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
835               MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
836             } else if (GlobalAddressSDNode *GA = 
837                   dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
838               MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
839                                                       GA->getOffset()));
840             } else {
841               BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
842               MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
843             }
844           }
845           break;
846         }
847         case 4:  // Addressing mode.
848           // The addressing mode has been selected, just add all of the
849           // operands to the machine instruction.
850           for (; NumVals; --NumVals, ++i)
851             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
852           break;
853         }
854       }
855       break;
856     }
857     }
858   }
859 }
860
861 void ScheduleDAG::EmitNoop() {
862   TII->insertNoop(*BB, BB->end());
863 }
864
865 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
866   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
867        I != E; ++I) {
868     if (I->isCtrl) continue;  // ignore chain preds
869     if (!I->Dep->Node) {
870       // Copy to physical register.
871       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
872       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
873       // Find the destination physical register.
874       unsigned Reg = 0;
875       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
876              EE = SU->Succs.end(); II != EE; ++II) {
877         if (I->Reg) {
878           Reg = I->Reg;
879           break;
880         }
881       }
882       assert(I->Reg && "Unknown physical register!");
883       TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
884                         SU->CopyDstRC, SU->CopySrcRC);
885     } else {
886       // Copy from physical register.
887       assert(I->Reg && "Unknown physical register!");
888       unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
889       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
890       assert(isNew && "Node emitted out of order - early");
891       TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
892                         SU->CopyDstRC, SU->CopySrcRC);
893     }
894     break;
895   }
896 }
897
898 /// EmitSchedule - Emit the machine code in scheduled order.
899 void ScheduleDAG::EmitSchedule() {
900   // If this is the first basic block in the function, and if it has live ins
901   // that need to be copied into vregs, emit the copies into the top of the
902   // block before emitting the code for the block.
903   if (&MF->front() == BB) {
904     for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
905          E = RegInfo.livein_end(); LI != E; ++LI)
906       if (LI->second) {
907         const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
908         TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
909                           LI->first, RC, RC);
910       }
911   }
912   
913   
914   // Finally, emit the code for all of the scheduled instructions.
915   DenseMap<SDOperand, unsigned> VRBaseMap;
916   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
917   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
918     if (SUnit *SU = Sequence[i]) {
919       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
920         EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
921       if (SU->Node)
922         EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
923       else
924         EmitCrossRCCopy(SU, CopyVRBaseMap);
925     } else {
926       // Null SUnit* is a noop.
927       EmitNoop();
928     }
929   }
930 }
931
932 /// dump - dump the schedule.
933 void ScheduleDAG::dumpSchedule() const {
934   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
935     if (SUnit *SU = Sequence[i])
936       SU->dump(&DAG);
937     else
938       cerr << "**** NOOP ****\n";
939   }
940 }
941
942
943 /// Run - perform scheduling.
944 ///
945 MachineBasicBlock *ScheduleDAG::Run() {
946   Schedule();
947   return BB;
948 }
949
950 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
951 /// a group of nodes flagged together.
952 void SUnit::dump(const SelectionDAG *G) const {
953   cerr << "SU(" << NodeNum << "): ";
954   if (Node)
955     Node->dump(G);
956   else
957     cerr << "CROSS RC COPY ";
958   cerr << "\n";
959   if (FlaggedNodes.size() != 0) {
960     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
961       cerr << "    ";
962       FlaggedNodes[i]->dump(G);
963       cerr << "\n";
964     }
965   }
966 }
967
968 void SUnit::dumpAll(const SelectionDAG *G) const {
969   dump(G);
970
971   cerr << "  # preds left       : " << NumPredsLeft << "\n";
972   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
973   cerr << "  Latency            : " << Latency << "\n";
974   cerr << "  Depth              : " << Depth << "\n";
975   cerr << "  Height             : " << Height << "\n";
976
977   if (Preds.size() != 0) {
978     cerr << "  Predecessors:\n";
979     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
980          I != E; ++I) {
981       if (I->isCtrl)
982         cerr << "   ch  #";
983       else
984         cerr << "   val #";
985       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
986       if (I->isSpecial)
987         cerr << " *";
988       cerr << "\n";
989     }
990   }
991   if (Succs.size() != 0) {
992     cerr << "  Successors:\n";
993     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
994          I != E; ++I) {
995       if (I->isCtrl)
996         cerr << "   ch  #";
997       else
998         cerr << "   val #";
999       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1000       if (I->isSpecial)
1001         cerr << " *";
1002       cerr << "\n";
1003     }
1004   }
1005   cerr << "\n";
1006 }