745367bd0078e7748f639f1911bcb2d07c352e44
[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/Type.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.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/ADT/Statistic.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 using namespace llvm;
32
33 STATISTIC(NumCommutes,   "Number of instructions commuted");
34
35 namespace {
36   static cl::opt<bool>
37   SchedLiveInCopies("schedule-livein-copies",
38                     cl::desc("Schedule copies of livein registers"),
39                     cl::init(false));
40 }
41
42 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
43                          const TargetMachine &tm)
44   : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
45   TII = TM.getInstrInfo();
46   MF  = &DAG.getMachineFunction();
47   TRI = TM.getRegisterInfo();
48   TLI = &DAG.getTargetLoweringInfo();
49   ConstPool = BB->getParent()->getConstantPool();
50 }
51
52 /// CheckForPhysRegDependency - Check if the dependency between def and use of
53 /// a specified operand is a physical register dependency. If so, returns the
54 /// register and the cost of copying the register.
55 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
56                                       const TargetRegisterInfo *TRI, 
57                                       const TargetInstrInfo *TII,
58                                       unsigned &PhysReg, int &Cost) {
59   if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
60     return;
61
62   unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
63   if (TargetRegisterInfo::isVirtualRegister(Reg))
64     return;
65
66   unsigned ResNo = Use->getOperand(2).ResNo;
67   if (Def->isTargetOpcode()) {
68     const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
69     if (ResNo >= II.getNumDefs() &&
70         II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
71       PhysReg = Reg;
72       const TargetRegisterClass *RC =
73         TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
74       Cost = RC->getCopyCost();
75     }
76   }
77 }
78
79 SUnit *ScheduleDAG::Clone(SUnit *Old) {
80   SUnit *SU = NewSUnit(Old->Node);
81   SU->OrigNode = Old->OrigNode;
82   SU->FlaggedNodes = Old->FlaggedNodes;
83   SU->Latency = Old->Latency;
84   SU->isTwoAddress = Old->isTwoAddress;
85   SU->isCommutable = Old->isCommutable;
86   SU->hasPhysRegDefs = Old->hasPhysRegDefs;
87   return SU;
88 }
89
90
91 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
92 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
93 /// together nodes with a single SUnit.
94 void ScheduleDAG::BuildSchedUnits() {
95   // Reserve entries in the vector for each of the SUnits we are creating.  This
96   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
97   // invalidated.
98   SUnits.reserve(DAG.allnodes_size());
99   
100   // During scheduling, the NodeId field of SDNode is used to map SDNodes
101   // to their associated SUnits by holding SUnits table indices. A value
102   // of -1 means the SDNode does not yet have an associated SUnit.
103   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
104        E = DAG.allnodes_end(); NI != E; ++NI)
105     NI->setNodeId(-1);
106
107   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
108        E = DAG.allnodes_end(); NI != E; ++NI) {
109     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
110       continue;
111     
112     // If this node has already been processed, stop now.
113     if (NI->getNodeId() != -1) continue;
114     
115     SUnit *NodeSUnit = NewSUnit(NI);
116     
117     // See if anything is flagged to this node, if so, add them to flagged
118     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
119     // are required the be the last operand and result of a node.
120     
121     // Scan up, adding flagged preds to FlaggedNodes.
122     SDNode *N = NI;
123     if (N->getNumOperands() &&
124         N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
125       do {
126         N = N->getOperand(N->getNumOperands()-1).Val;
127         NodeSUnit->FlaggedNodes.push_back(N);
128         assert(N->getNodeId() == -1 && "Node already inserted!");
129         N->setNodeId(NodeSUnit->NodeNum);
130       } while (N->getNumOperands() &&
131                N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
132       std::reverse(NodeSUnit->FlaggedNodes.begin(),
133                    NodeSUnit->FlaggedNodes.end());
134     }
135     
136     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
137     // have a user of the flag operand.
138     N = NI;
139     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
140       SDOperand FlagVal(N, N->getNumValues()-1);
141       
142       // There are either zero or one users of the Flag result.
143       bool HasFlagUse = false;
144       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
145            UI != E; ++UI)
146         if (FlagVal.isOperandOf(UI->getUser())) {
147           HasFlagUse = true;
148           NodeSUnit->FlaggedNodes.push_back(N);
149           assert(N->getNodeId() == -1 && "Node already inserted!");
150           N->setNodeId(NodeSUnit->NodeNum);
151           N = UI->getUser();
152           break;
153         }
154       if (!HasFlagUse) break;
155     }
156     
157     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
158     // Update the SUnit
159     NodeSUnit->Node = N;
160     assert(N->getNodeId() == -1 && "Node already inserted!");
161     N->setNodeId(NodeSUnit->NodeNum);
162
163     ComputeLatency(NodeSUnit);
164   }
165   
166   // Pass 2: add the preds, succs, etc.
167   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
168     SUnit *SU = &SUnits[su];
169     SDNode *MainNode = SU->Node;
170     
171     if (MainNode->isTargetOpcode()) {
172       unsigned Opc = MainNode->getTargetOpcode();
173       const TargetInstrDesc &TID = TII->get(Opc);
174       for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
175         if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
176           SU->isTwoAddress = true;
177           break;
178         }
179       }
180       if (TID.isCommutable())
181         SU->isCommutable = true;
182     }
183     
184     // Find all predecessors and successors of the group.
185     // Temporarily add N to make code simpler.
186     SU->FlaggedNodes.push_back(MainNode);
187     
188     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
189       SDNode *N = SU->FlaggedNodes[n];
190       if (N->isTargetOpcode() &&
191           TII->get(N->getTargetOpcode()).getImplicitDefs() &&
192           CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
193         SU->hasPhysRegDefs = true;
194       
195       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
196         SDNode *OpN = N->getOperand(i).Val;
197         if (isPassiveNode(OpN)) continue;   // Not scheduled.
198         SUnit *OpSU = &SUnits[OpN->getNodeId()];
199         assert(OpSU && "Node has no SUnit!");
200         if (OpSU == SU) continue;           // In the same group.
201
202         MVT OpVT = N->getOperand(i).getValueType();
203         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
204         bool isChain = OpVT == MVT::Other;
205
206         unsigned PhysReg = 0;
207         int Cost = 1;
208         // Determine if this is a physical register dependency.
209         CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
210         SU->addPred(OpSU, isChain, false, PhysReg, Cost);
211       }
212     }
213     
214     // Remove MainNode from FlaggedNodes again.
215     SU->FlaggedNodes.pop_back();
216   }
217   
218   return;
219 }
220
221 void ScheduleDAG::ComputeLatency(SUnit *SU) {
222   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
223   
224   // Compute the latency for the node.  We use the sum of the latencies for
225   // all nodes flagged together into this SUnit.
226   if (InstrItins.isEmpty()) {
227     // No latency information.
228     SU->Latency = 1;
229   } else {
230     SU->Latency = 0;
231     if (SU->Node->isTargetOpcode()) {
232       unsigned SchedClass =
233         TII->get(SU->Node->getTargetOpcode()).getSchedClass();
234       const InstrStage *S = InstrItins.begin(SchedClass);
235       const InstrStage *E = InstrItins.end(SchedClass);
236       for (; S != E; ++S)
237         SU->Latency += S->Cycles;
238     }
239     for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
240       SDNode *FNode = SU->FlaggedNodes[i];
241       if (FNode->isTargetOpcode()) {
242         unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
243         const InstrStage *S = InstrItins.begin(SchedClass);
244         const InstrStage *E = InstrItins.end(SchedClass);
245         for (; S != E; ++S)
246           SU->Latency += S->Cycles;
247       }
248     }
249   }
250 }
251
252 /// CalculateDepths - compute depths using algorithms for the longest
253 /// paths in the DAG
254 void ScheduleDAG::CalculateDepths() {
255   unsigned DAGSize = SUnits.size();
256   std::vector<unsigned> InDegree(DAGSize);
257   std::vector<SUnit*> WorkList;
258   WorkList.reserve(DAGSize);
259
260   // Initialize the data structures
261   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
262     SUnit *SU = &SUnits[i];
263     int NodeNum = SU->NodeNum;
264     unsigned Degree = SU->Preds.size();
265     InDegree[NodeNum] = Degree;
266     SU->Depth = 0;
267
268     // Is it a node without dependencies?
269     if (Degree == 0) {
270         assert(SU->Preds.empty() && "SUnit should have no predecessors");
271         // Collect leaf nodes
272         WorkList.push_back(SU);
273     }
274   }
275
276   // Process nodes in the topological order
277   while (!WorkList.empty()) {
278     SUnit *SU = WorkList.back();
279     WorkList.pop_back();
280     unsigned &SUDepth  = SU->Depth;
281
282     // Use dynamic programming:
283     // When current node is being processed, all of its dependencies
284     // are already processed.
285     // So, just iterate over all predecessors and take the longest path
286     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
287          I != E; ++I) {
288       unsigned PredDepth = I->Dep->Depth;
289       if (PredDepth+1 > SUDepth) {
290           SUDepth = PredDepth + 1;
291       }
292     }
293
294     // Update InDegrees of all nodes depending on current SUnit
295     for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
296          I != E; ++I) {
297       SUnit *SU = I->Dep;
298       if (!--InDegree[SU->NodeNum])
299         // If all dependencies of the node are processed already,
300         // then the longest path for the node can be computed now
301         WorkList.push_back(SU);
302     }
303   }
304 }
305
306 /// CalculateHeights - compute heights using algorithms for the longest
307 /// paths in the DAG
308 void ScheduleDAG::CalculateHeights() {
309   unsigned DAGSize = SUnits.size();
310   std::vector<unsigned> InDegree(DAGSize);
311   std::vector<SUnit*> WorkList;
312   WorkList.reserve(DAGSize);
313
314   // Initialize the data structures
315   for (unsigned i = 0, e = DAGSize; i != e; ++i) {
316     SUnit *SU = &SUnits[i];
317     int NodeNum = SU->NodeNum;
318     unsigned Degree = SU->Succs.size();
319     InDegree[NodeNum] = Degree;
320     SU->Height = 0;
321
322     // Is it a node without dependencies?
323     if (Degree == 0) {
324         assert(SU->Succs.empty() && "Something wrong");
325         assert(WorkList.empty() && "Should be empty");
326         // Collect leaf nodes
327         WorkList.push_back(SU);
328     }
329   }
330
331   // Process nodes in the topological order
332   while (!WorkList.empty()) {
333     SUnit *SU = WorkList.back();
334     WorkList.pop_back();
335     unsigned &SUHeight  = SU->Height;
336
337     // Use dynamic programming:
338     // When current node is being processed, all of its dependencies
339     // are already processed.
340     // So, just iterate over all successors and take the longest path
341     for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
342          I != E; ++I) {
343       unsigned SuccHeight = I->Dep->Height;
344       if (SuccHeight+1 > SUHeight) {
345           SUHeight = SuccHeight + 1;
346       }
347     }
348
349     // Update InDegrees of all nodes depending on current SUnit
350     for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
351          I != E; ++I) {
352       SUnit *SU = I->Dep;
353       if (!--InDegree[SU->NodeNum])
354         // If all dependencies of the node are processed already,
355         // then the longest path for the node can be computed now
356         WorkList.push_back(SU);
357     }
358   }
359 }
360
361 /// CountResults - The results of target nodes have register or immediate
362 /// operands first, then an optional chain, and optional flag operands (which do
363 /// not go into the resulting MachineInstr).
364 unsigned ScheduleDAG::CountResults(SDNode *Node) {
365   unsigned N = Node->getNumValues();
366   while (N && Node->getValueType(N - 1) == MVT::Flag)
367     --N;
368   if (N && Node->getValueType(N - 1) == MVT::Other)
369     --N;    // Skip over chain result.
370   return N;
371 }
372
373 /// CountOperands - The inputs to target nodes have any actual inputs first,
374 /// followed by special operands that describe memory references, then an
375 /// optional chain operand, then flag operands.  Compute the number of
376 /// actual operands that will go into the resulting MachineInstr.
377 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
378   unsigned N = ComputeMemOperandsEnd(Node);
379   while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
380     --N; // Ignore MEMOPERAND nodes
381   return N;
382 }
383
384 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
385 /// operand
386 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
387   unsigned N = Node->getNumOperands();
388   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
389     --N;
390   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
391     --N; // Ignore chain if it exists.
392   return N;
393 }
394
395 static const TargetRegisterClass *getInstrOperandRegClass(
396         const TargetRegisterInfo *TRI, 
397         const TargetInstrInfo *TII,
398         const TargetInstrDesc &II,
399         unsigned Op) {
400   if (Op >= II.getNumOperands()) {
401     assert(II.isVariadic() && "Invalid operand # of instruction");
402     return NULL;
403   }
404   if (II.OpInfo[Op].isLookupPtrRegClass())
405     return TII->getPointerRegClass();
406   return TRI->getRegClass(II.OpInfo[Op].RegClass);
407 }
408
409 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
410                                   bool IsClone, unsigned SrcReg,
411                                   DenseMap<SDOperand, unsigned> &VRBaseMap) {
412   unsigned VRBase = 0;
413   if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
414     // Just use the input register directly!
415     if (IsClone)
416       VRBaseMap.erase(SDOperand(Node, ResNo));
417     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
418     isNew = isNew; // Silence compiler warning.
419     assert(isNew && "Node emitted out of order - early");
420     return;
421   }
422
423   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
424   // the CopyToReg'd destination register instead of creating a new vreg.
425   bool MatchReg = true;
426   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
427        UI != E; ++UI) {
428     SDNode *Use = UI->getUser();
429     bool Match = true;
430     if (Use->getOpcode() == ISD::CopyToReg && 
431         Use->getOperand(2).Val == Node &&
432         Use->getOperand(2).ResNo == ResNo) {
433       unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
434       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
435         VRBase = DestReg;
436         Match = false;
437       } else if (DestReg != SrcReg)
438         Match = false;
439     } else {
440       for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
441         SDOperand Op = Use->getOperand(i);
442         if (Op.Val != Node || Op.ResNo != ResNo)
443           continue;
444         MVT VT = Node->getValueType(Op.ResNo);
445         if (VT != MVT::Other && VT != MVT::Flag)
446           Match = false;
447       }
448     }
449     MatchReg &= Match;
450     if (VRBase)
451       break;
452   }
453
454   const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
455   SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, Node->getValueType(ResNo));
456   
457   // Figure out the register class to create for the destreg.
458   if (VRBase) {
459     DstRC = MRI.getRegClass(VRBase);
460   } else {
461     DstRC = TLI->getRegClassFor(Node->getValueType(ResNo));
462   }
463     
464   // If all uses are reading from the src physical register and copying the
465   // register is either impossible or very expensive, then don't create a copy.
466   if (MatchReg && SrcRC->getCopyCost() < 0) {
467     VRBase = SrcReg;
468   } else {
469     // Create the reg, emit the copy.
470     VRBase = MRI.createVirtualRegister(DstRC);
471     TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
472   }
473
474   if (IsClone)
475     VRBaseMap.erase(SDOperand(Node, ResNo));
476   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
477   isNew = isNew; // Silence compiler warning.
478   assert(isNew && "Node emitted out of order - early");
479 }
480
481 /// getDstOfCopyToRegUse - If the only use of the specified result number of
482 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
483 unsigned ScheduleDAG::getDstOfOnlyCopyToRegUse(SDNode *Node,
484                                                unsigned ResNo) const {
485   if (!Node->hasOneUse())
486     return 0;
487
488   SDNode *Use = Node->use_begin()->getUser();
489   if (Use->getOpcode() == ISD::CopyToReg && 
490       Use->getOperand(2).Val == Node &&
491       Use->getOperand(2).ResNo == ResNo) {
492     unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
493     if (TargetRegisterInfo::isVirtualRegister(Reg))
494       return Reg;
495   }
496   return 0;
497 }
498
499 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
500                                  const TargetInstrDesc &II,
501                                  DenseMap<SDOperand, unsigned> &VRBaseMap) {
502   assert(Node->getTargetOpcode() != TargetInstrInfo::IMPLICIT_DEF &&
503          "IMPLICIT_DEF should have been handled as a special case elsewhere!");
504
505   for (unsigned i = 0; i < II.getNumDefs(); ++i) {
506     // If the specific node value is only used by a CopyToReg and the dest reg
507     // is a vreg, use the CopyToReg'd destination register instead of creating
508     // a new vreg.
509     unsigned VRBase = 0;
510     for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
511          UI != E; ++UI) {
512       SDNode *Use = UI->getUser();
513       if (Use->getOpcode() == ISD::CopyToReg && 
514           Use->getOperand(2).Val == Node &&
515           Use->getOperand(2).ResNo == i) {
516         unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
517         if (TargetRegisterInfo::isVirtualRegister(Reg)) {
518           VRBase = Reg;
519           MI->addOperand(MachineOperand::CreateReg(Reg, true));
520           break;
521         }
522       }
523     }
524
525     // Create the result registers for this node and add the result regs to
526     // the machine instruction.
527     if (VRBase == 0) {
528       const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
529       assert(RC && "Isn't a register operand!");
530       VRBase = MRI.createVirtualRegister(RC);
531       MI->addOperand(MachineOperand::CreateReg(VRBase, true));
532     }
533
534     bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
535     isNew = isNew; // Silence compiler warning.
536     assert(isNew && "Node emitted out of order - early");
537   }
538 }
539
540 /// getVR - Return the virtual register corresponding to the specified result
541 /// of the specified node.
542 unsigned ScheduleDAG::getVR(SDOperand Op,
543                             DenseMap<SDOperand, unsigned> &VRBaseMap) {
544   if (Op.isTargetOpcode() &&
545       Op.getTargetOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
546     // Add an IMPLICIT_DEF instruction before every use.
547     unsigned VReg = getDstOfOnlyCopyToRegUse(Op.Val, Op.ResNo);
548     // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
549     // does not include operand register class info.
550     if (!VReg) {
551       const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
552       VReg = MRI.createVirtualRegister(RC);
553     }
554     BuildMI(BB, TII->get(TargetInstrInfo::IMPLICIT_DEF), VReg);
555     return VReg;
556   }
557
558   DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
559   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
560   return I->second;
561 }
562
563
564 /// AddOperand - Add the specified operand to the specified machine instr.  II
565 /// specifies the instruction information for the node, and IIOpNum is the
566 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
567 /// assertions only.
568 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
569                              unsigned IIOpNum,
570                              const TargetInstrDesc *II,
571                              DenseMap<SDOperand, unsigned> &VRBaseMap) {
572   if (Op.isTargetOpcode()) {
573     // Note that this case is redundant with the final else block, but we
574     // include it because it is the most common and it makes the logic
575     // simpler here.
576     assert(Op.getValueType() != MVT::Other &&
577            Op.getValueType() != MVT::Flag &&
578            "Chain and flag operands should occur at end of operand list!");
579     // Get/emit the operand.
580     unsigned VReg = getVR(Op, VRBaseMap);
581     const TargetInstrDesc &TID = MI->getDesc();
582     bool isOptDef = IIOpNum < TID.getNumOperands() &&
583       TID.OpInfo[IIOpNum].isOptionalDef();
584     MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
585     
586     // Verify that it is right.
587     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
588 #ifndef NDEBUG
589     if (II) {
590       // There may be no register class for this operand if it is a variadic
591       // argument (RC will be NULL in this case).  In this case, we just assume
592       // the regclass is ok.
593       const TargetRegisterClass *RC =
594                           getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
595       assert((RC || II->isVariadic()) && "Expected reg class info!");
596       const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
597       if (RC && VRC != RC) {
598         cerr << "Register class of operand and regclass of use don't agree!\n";
599         cerr << "Operand = " << IIOpNum << "\n";
600         cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
601         cerr << "MI = "; MI->print(cerr);
602         cerr << "VReg = " << VReg << "\n";
603         cerr << "VReg RegClass     size = " << VRC->getSize()
604              << ", align = " << VRC->getAlignment() << "\n";
605         cerr << "Expected RegClass size = " << RC->getSize()
606              << ", align = " << RC->getAlignment() << "\n";
607         cerr << "Fatal error, aborting.\n";
608         abort();
609       }
610     }
611 #endif
612   } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
613     MI->addOperand(MachineOperand::CreateImm(C->getValue()));
614   } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
615     ConstantFP *CFP = ConstantFP::get(F->getValueAPF());
616     MI->addOperand(MachineOperand::CreateFPImm(CFP));
617   } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
618     MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
619   } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
620     MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
621   } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
622     MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
623   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
624     MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
625   } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
626     MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
627   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
628     int Offset = CP->getOffset();
629     unsigned Align = CP->getAlignment();
630     const Type *Type = CP->getType();
631     // MachineConstantPool wants an explicit alignment.
632     if (Align == 0) {
633       Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
634       if (Align == 0) {
635         // Alignment of vector types.  FIXME!
636         Align = TM.getTargetData()->getABITypeSize(Type);
637         Align = Log2_64(Align);
638       }
639     }
640     
641     unsigned Idx;
642     if (CP->isMachineConstantPoolEntry())
643       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
644     else
645       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
646     MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
647   } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
648     MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
649   } else {
650     assert(Op.getValueType() != MVT::Other &&
651            Op.getValueType() != MVT::Flag &&
652            "Chain and flag operands should occur at end of operand list!");
653     unsigned VReg = getVR(Op, VRBaseMap);
654     MI->addOperand(MachineOperand::CreateReg(VReg, false));
655     
656     // Verify that it is right.  Note that the reg class of the physreg and the
657     // vreg don't necessarily need to match, but the target copy insertion has
658     // to be able to handle it.  This handles things like copies from ST(0) to
659     // an FP vreg on x86.
660     assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
661     if (II && !II->isVariadic()) {
662       assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
663              "Don't have operand info for this instruction!");
664     }
665   }
666   
667 }
668
669 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO) {
670   MI->addMemOperand(MO);
671 }
672
673 // Returns the Register Class of a subregister
674 static const TargetRegisterClass *getSubRegisterRegClass(
675         const TargetRegisterClass *TRC,
676         unsigned SubIdx) {
677   // Pick the register class of the subregister
678   TargetRegisterInfo::regclass_iterator I =
679     TRC->subregclasses_begin() + SubIdx-1;
680   assert(I < TRC->subregclasses_end() && 
681          "Invalid subregister index for register class");
682   return *I;
683 }
684
685 static const TargetRegisterClass *getSuperregRegisterClass(
686         const TargetRegisterClass *TRC,
687         unsigned SubIdx,
688         MVT VT) {
689   // Pick the register class of the superegister for this type
690   for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
691          E = TRC->superregclasses_end(); I != E; ++I)
692     if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
693       return *I;
694   assert(false && "Couldn't find the register class");
695   return 0;
696 }
697
698 /// EmitSubregNode - Generate machine code for subreg nodes.
699 ///
700 void ScheduleDAG::EmitSubregNode(SDNode *Node, 
701                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
702   unsigned VRBase = 0;
703   unsigned Opc = Node->getTargetOpcode();
704   
705   // If the node is only used by a CopyToReg and the dest reg is a vreg, use
706   // the CopyToReg'd destination register instead of creating a new vreg.
707   for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
708        UI != E; ++UI) {
709     SDNode *Use = UI->getUser();
710     if (Use->getOpcode() == ISD::CopyToReg && 
711         Use->getOperand(2).Val == Node) {
712       unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
713       if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
714         VRBase = DestReg;
715         break;
716       }
717     }
718   }
719   
720   if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
721     unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
722
723     // Create the extract_subreg machine instruction.
724     MachineInstr *MI = BuildMI(TII->get(TargetInstrInfo::EXTRACT_SUBREG));
725
726     // Figure out the register class to create for the destreg.
727     unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
728     const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
729     const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
730
731     if (VRBase) {
732       // Grab the destination register
733 #ifndef NDEBUG
734       const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
735       assert(SRC && DRC && SRC == DRC && 
736              "Source subregister and destination must have the same class");
737 #endif
738     } else {
739       // Create the reg
740       assert(SRC && "Couldn't find source register class");
741       VRBase = MRI.createVirtualRegister(SRC);
742     }
743     
744     // Add def, source, and subreg index
745     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
746     AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
747     MI->addOperand(MachineOperand::CreateImm(SubIdx));
748     BB->push_back(MI);    
749   } else if (Opc == TargetInstrInfo::INSERT_SUBREG ||
750              Opc == TargetInstrInfo::SUBREG_TO_REG) {
751     SDOperand N0 = Node->getOperand(0);
752     SDOperand N1 = Node->getOperand(1);
753     SDOperand N2 = Node->getOperand(2);
754     unsigned SubReg = getVR(N1, VRBaseMap);
755     unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
756     
757       
758     // Figure out the register class to create for the destreg.
759     const TargetRegisterClass *TRC = 0;
760     if (VRBase) {
761       TRC = MRI.getRegClass(VRBase);
762     } else {
763       TRC = getSuperregRegisterClass(MRI.getRegClass(SubReg), SubIdx, 
764                                      Node->getValueType(0));
765       assert(TRC && "Couldn't determine register class for insert_subreg");
766       VRBase = MRI.createVirtualRegister(TRC); // Create the reg
767     }
768     
769     // Create the insert_subreg or subreg_to_reg machine instruction.
770     MachineInstr *MI = BuildMI(TII->get(Opc));
771     MI->addOperand(MachineOperand::CreateReg(VRBase, true));
772     
773     // If creating a subreg_to_reg, then the first input operand
774     // is an implicit value immediate, otherwise it's a register
775     if (Opc == TargetInstrInfo::SUBREG_TO_REG) {
776       const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
777       MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
778     } else
779       AddOperand(MI, N0, 0, 0, VRBaseMap);
780     // Add the subregster being inserted
781     AddOperand(MI, N1, 0, 0, VRBaseMap);
782     MI->addOperand(MachineOperand::CreateImm(SubIdx));
783     BB->push_back(MI);
784   } else
785     assert(0 && "Node is not insert_subreg, extract_subreg, or subreg_to_reg");
786      
787   bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
788   isNew = isNew; // Silence compiler warning.
789   assert(isNew && "Node emitted out of order - early");
790 }
791
792 /// EmitNode - Generate machine code for an node and needed dependencies.
793 ///
794 void ScheduleDAG::EmitNode(SDNode *Node, bool IsClone,
795                            DenseMap<SDOperand, unsigned> &VRBaseMap) {
796   // If machine instruction
797   if (Node->isTargetOpcode()) {
798     unsigned Opc = Node->getTargetOpcode();
799     
800     // Handle subreg insert/extract specially
801     if (Opc == TargetInstrInfo::EXTRACT_SUBREG || 
802         Opc == TargetInstrInfo::INSERT_SUBREG ||
803         Opc == TargetInstrInfo::SUBREG_TO_REG) {
804       EmitSubregNode(Node, VRBaseMap);
805       return;
806     }
807
808     if (Opc == TargetInstrInfo::IMPLICIT_DEF)
809       // We want a unique VR for each IMPLICIT_DEF use.
810       return;
811     
812     const TargetInstrDesc &II = TII->get(Opc);
813     unsigned NumResults = CountResults(Node);
814     unsigned NodeOperands = CountOperands(Node);
815     unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
816     bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
817                           II.getImplicitDefs() != 0;
818 #ifndef NDEBUG
819     unsigned NumMIOperands = NodeOperands + NumResults;
820     assert((II.getNumOperands() == NumMIOperands ||
821             HasPhysRegOuts || II.isVariadic()) &&
822            "#operands for dag node doesn't match .td file!"); 
823 #endif
824
825     // Create the new machine instruction.
826     MachineInstr *MI = BuildMI(II);
827     
828     // Add result register values for things that are defined by this
829     // instruction.
830     if (NumResults)
831       CreateVirtualRegisters(Node, MI, II, VRBaseMap);
832     
833     // Emit all of the actual operands of this instruction, adding them to the
834     // instruction as appropriate.
835     for (unsigned i = 0; i != NodeOperands; ++i)
836       AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
837
838     // Emit all of the memory operands of this instruction
839     for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
840       AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
841
842     // Commute node if it has been determined to be profitable.
843     if (CommuteSet.count(Node)) {
844       MachineInstr *NewMI = TII->commuteInstruction(MI);
845       if (NewMI == 0)
846         DOUT << "Sched: COMMUTING FAILED!\n";
847       else {
848         DOUT << "Sched: COMMUTED TO: " << *NewMI;
849         if (MI != NewMI) {
850           delete MI;
851           MI = NewMI;
852         }
853         ++NumCommutes;
854       }
855     }
856
857     if (II.usesCustomDAGSchedInsertionHook())
858       // Insert this instruction into the basic block using a target
859       // specific inserter which may returns a new basic block.
860       BB = TLI->EmitInstrWithCustomInserter(MI, BB);
861     else
862       BB->push_back(MI);
863
864     // Additional results must be an physical register def.
865     if (HasPhysRegOuts) {
866       for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
867         unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
868         if (Node->hasAnyUseOfValue(i))
869           EmitCopyFromReg(Node, i, IsClone, Reg, VRBaseMap);
870       }
871     }
872   } else {
873     switch (Node->getOpcode()) {
874     default:
875 #ifndef NDEBUG
876       Node->dump(&DAG);
877 #endif
878       assert(0 && "This target-independent node should have been selected!");
879       break;
880     case ISD::EntryToken:
881       assert(0 && "EntryToken should have been excluded from the schedule!");
882       break;
883     case ISD::TokenFactor: // fall thru
884     case ISD::LABEL:
885     case ISD::DECLARE:
886     case ISD::SRCVALUE:
887       break;
888     case ISD::CopyToReg: {
889       unsigned SrcReg;
890       SDOperand SrcVal = Node->getOperand(2);
891       if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
892         SrcReg = R->getReg();
893       else
894         SrcReg = getVR(SrcVal, VRBaseMap);
895       
896       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
897       if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
898         break;
899       
900       const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
901       // Get the register classes of the src/dst.
902       if (TargetRegisterInfo::isVirtualRegister(SrcReg))
903         SrcTRC = MRI.getRegClass(SrcReg);
904       else
905         SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
906
907       if (TargetRegisterInfo::isVirtualRegister(DestReg))
908         DstTRC = MRI.getRegClass(DestReg);
909       else
910         DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
911                                             Node->getOperand(1).getValueType());
912       TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
913       break;
914     }
915     case ISD::CopyFromReg: {
916       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
917       EmitCopyFromReg(Node, 0, IsClone, SrcReg, VRBaseMap);
918       break;
919     }
920     case ISD::INLINEASM: {
921       unsigned NumOps = Node->getNumOperands();
922       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
923         --NumOps;  // Ignore the flag operand.
924       
925       // Create the inline asm machine instruction.
926       MachineInstr *MI = BuildMI(TII->get(TargetInstrInfo::INLINEASM));
927
928       // Add the asm string as an external symbol operand.
929       const char *AsmStr =
930         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
931       MI->addOperand(MachineOperand::CreateES(AsmStr));
932       
933       // Add all of the operand registers to the instruction.
934       for (unsigned i = 2; i != NumOps;) {
935         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
936         unsigned NumVals = Flags >> 3;
937         
938         MI->addOperand(MachineOperand::CreateImm(Flags));
939         ++i;  // Skip the ID value.
940         
941         switch (Flags & 7) {
942         default: assert(0 && "Bad flags!");
943         case 1:  // Use of register.
944           for (; NumVals; --NumVals, ++i) {
945             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
946             MI->addOperand(MachineOperand::CreateReg(Reg, false));
947           }
948           break;
949         case 2:   // Def of register.
950           for (; NumVals; --NumVals, ++i) {
951             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
952             MI->addOperand(MachineOperand::CreateReg(Reg, true));
953           }
954           break;
955         case 3: { // Immediate.
956           for (; NumVals; --NumVals, ++i) {
957             if (ConstantSDNode *CS =
958                    dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
959               MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
960             } else if (GlobalAddressSDNode *GA = 
961                   dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
962               MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
963                                                       GA->getOffset()));
964             } else {
965               BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
966               MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
967             }
968           }
969           break;
970         }
971         case 4:  // Addressing mode.
972           // The addressing mode has been selected, just add all of the
973           // operands to the machine instruction.
974           for (; NumVals; --NumVals, ++i)
975             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
976           break;
977         }
978       }
979       BB->push_back(MI);
980       break;
981     }
982     }
983   }
984 }
985
986 void ScheduleDAG::EmitNoop() {
987   TII->insertNoop(*BB, BB->end());
988 }
989
990 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
991                                   DenseMap<SUnit*, unsigned> &VRBaseMap) {
992   for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
993        I != E; ++I) {
994     if (I->isCtrl) continue;  // ignore chain preds
995     if (!I->Dep->Node) {
996       // Copy to physical register.
997       DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
998       assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
999       // Find the destination physical register.
1000       unsigned Reg = 0;
1001       for (SUnit::const_succ_iterator II = SU->Succs.begin(),
1002              EE = SU->Succs.end(); II != EE; ++II) {
1003         if (I->Reg) {
1004           Reg = I->Reg;
1005           break;
1006         }
1007       }
1008       assert(I->Reg && "Unknown physical register!");
1009       TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
1010                         SU->CopyDstRC, SU->CopySrcRC);
1011     } else {
1012       // Copy from physical register.
1013       assert(I->Reg && "Unknown physical register!");
1014       unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
1015       bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
1016       isNew = isNew; // Silence compiler warning.
1017       assert(isNew && "Node emitted out of order - early");
1018       TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
1019                         SU->CopyDstRC, SU->CopySrcRC);
1020     }
1021     break;
1022   }
1023 }
1024
1025 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
1026 /// physical register has only a single copy use, then coalesced the copy
1027 /// if possible.
1028 void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
1029                                  MachineBasicBlock::iterator &InsertPos,
1030                                  unsigned VirtReg, unsigned PhysReg,
1031                                  const TargetRegisterClass *RC,
1032                                  DenseMap<MachineInstr*, unsigned> &CopyRegMap){
1033   unsigned NumUses = 0;
1034   MachineInstr *UseMI = NULL;
1035   for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
1036          UE = MRI.use_end(); UI != UE; ++UI) {
1037     UseMI = &*UI;
1038     if (++NumUses > 1)
1039       break;
1040   }
1041
1042   // If the number of uses is not one, or the use is not a move instruction,
1043   // don't coalesce. Also, only coalesce away a virtual register to virtual
1044   // register copy.
1045   bool Coalesced = false;
1046   unsigned SrcReg, DstReg;
1047   if (NumUses == 1 &&
1048       TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
1049       TargetRegisterInfo::isVirtualRegister(DstReg)) {
1050     VirtReg = DstReg;
1051     Coalesced = true;
1052   }
1053
1054   // Now find an ideal location to insert the copy.
1055   MachineBasicBlock::iterator Pos = InsertPos;
1056   while (Pos != MBB->begin()) {
1057     MachineInstr *PrevMI = prior(Pos);
1058     DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
1059     // copyRegToReg might emit multiple instructions to do a copy.
1060     unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
1061     if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
1062       // This is what the BB looks like right now:
1063       // r1024 = mov r0
1064       // ...
1065       // r1    = mov r1024
1066       //
1067       // We want to insert "r1025 = mov r1". Inserting this copy below the
1068       // move to r1024 makes it impossible for that move to be coalesced.
1069       //
1070       // r1025 = mov r1
1071       // r1024 = mov r0
1072       // ...
1073       // r1    = mov 1024
1074       // r2    = mov 1025
1075       break; // Woot! Found a good location.
1076     --Pos;
1077   }
1078
1079   TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
1080   CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
1081   if (Coalesced) {
1082     if (&*InsertPos == UseMI) ++InsertPos;
1083     MBB->erase(UseMI);
1084   }
1085 }
1086
1087 /// EmitLiveInCopies - If this is the first basic block in the function,
1088 /// and if it has live ins that need to be copied into vregs, emit the
1089 /// copies into the top of the block.
1090 void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
1091   DenseMap<MachineInstr*, unsigned> CopyRegMap;
1092   MachineBasicBlock::iterator InsertPos = MBB->begin();
1093   for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1094          E = MRI.livein_end(); LI != E; ++LI)
1095     if (LI->second) {
1096       const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1097       EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
1098     }
1099 }
1100
1101 /// EmitSchedule - Emit the machine code in scheduled order.
1102 void ScheduleDAG::EmitSchedule() {
1103   bool isEntryBB = &MF->front() == BB;
1104
1105   if (isEntryBB && !SchedLiveInCopies) {
1106     // If this is the first basic block in the function, and if it has live ins
1107     // that need to be copied into vregs, emit the copies into the top of the
1108     // block before emitting the code for the block.
1109     for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1110            E = MRI.livein_end(); LI != E; ++LI)
1111       if (LI->second) {
1112         const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1113         TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1114                           LI->first, RC, RC);
1115       }
1116   }
1117
1118   // Finally, emit the code for all of the scheduled instructions.
1119   DenseMap<SDOperand, unsigned> VRBaseMap;
1120   DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1121   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1122     SUnit *SU = Sequence[i];
1123     if (!SU) {
1124       // Null SUnit* is a noop.
1125       EmitNoop();
1126       continue;
1127     }
1128     for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1129       EmitNode(SU->FlaggedNodes[j], SU->OrigNode != SU, VRBaseMap);
1130     if (!SU->Node)
1131       EmitCrossRCCopy(SU, CopyVRBaseMap);
1132     else
1133       EmitNode(SU->Node, SU->OrigNode != SU, VRBaseMap);
1134   }
1135
1136   if (isEntryBB && SchedLiveInCopies)
1137     EmitLiveInCopies(MF->begin());
1138 }
1139
1140 /// dump - dump the schedule.
1141 void ScheduleDAG::dumpSchedule() const {
1142   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1143     if (SUnit *SU = Sequence[i])
1144       SU->dump(&DAG);
1145     else
1146       cerr << "**** NOOP ****\n";
1147   }
1148 }
1149
1150
1151 /// Run - perform scheduling.
1152 ///
1153 MachineBasicBlock *ScheduleDAG::Run() {
1154   Schedule();
1155   return BB;
1156 }
1157
1158 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1159 /// a group of nodes flagged together.
1160 void SUnit::dump(const SelectionDAG *G) const {
1161   cerr << "SU(" << NodeNum << "): ";
1162   if (Node)
1163     Node->dump(G);
1164   else
1165     cerr << "CROSS RC COPY ";
1166   cerr << "\n";
1167   if (FlaggedNodes.size() != 0) {
1168     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1169       cerr << "    ";
1170       FlaggedNodes[i]->dump(G);
1171       cerr << "\n";
1172     }
1173   }
1174 }
1175
1176 void SUnit::dumpAll(const SelectionDAG *G) const {
1177   dump(G);
1178
1179   cerr << "  # preds left       : " << NumPredsLeft << "\n";
1180   cerr << "  # succs left       : " << NumSuccsLeft << "\n";
1181   cerr << "  Latency            : " << Latency << "\n";
1182   cerr << "  Depth              : " << Depth << "\n";
1183   cerr << "  Height             : " << Height << "\n";
1184
1185   if (Preds.size() != 0) {
1186     cerr << "  Predecessors:\n";
1187     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1188          I != E; ++I) {
1189       if (I->isCtrl)
1190         cerr << "   ch  #";
1191       else
1192         cerr << "   val #";
1193       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1194       if (I->isSpecial)
1195         cerr << " *";
1196       cerr << "\n";
1197     }
1198   }
1199   if (Succs.size() != 0) {
1200     cerr << "  Successors:\n";
1201     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1202          I != E; ++I) {
1203       if (I->isCtrl)
1204         cerr << "   ch  #";
1205       else
1206         cerr << "   val #";
1207       cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1208       if (I->isSpecial)
1209         cerr << " *";
1210       cerr << "\n";
1211     }
1212   }
1213   cerr << "\n";
1214 }