Changes to use operand constraints to process two-address instructions.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / ScheduleDAG.cpp
1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements a simple two pass scheduler.  The first pass attempts to push
11 // backward any lengthy instructions and critical paths.  The second pass packs
12 // instructions into semi-optimal time slots.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "sched"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MathExtras.h"
27 #include <iostream>
28 using namespace llvm;
29
30
31 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
32 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
33 /// together nodes with a single SUnit.
34 void ScheduleDAG::BuildSchedUnits() {
35   // Reserve entries in the vector for each of the SUnits we are creating.  This
36   // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
37   // invalidated.
38   SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
39   
40   const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
41   
42   for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
43        E = DAG.allnodes_end(); NI != E; ++NI) {
44     if (isPassiveNode(NI))  // Leaf node, e.g. a TargetImmediate.
45       continue;
46     
47     // If this node has already been processed, stop now.
48     if (SUnitMap[NI]) continue;
49     
50     SUnit *NodeSUnit = NewSUnit(NI);
51     
52     // See if anything is flagged to this node, if so, add them to flagged
53     // nodes.  Nodes can have at most one flag input and one flag output.  Flags
54     // are required the be the last operand and result of a node.
55     
56     // Scan up, adding flagged preds to FlaggedNodes.
57     SDNode *N = NI;
58     if (N->getNumOperands() &&
59         N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
60       do {
61         N = N->getOperand(N->getNumOperands()-1).Val;
62         NodeSUnit->FlaggedNodes.push_back(N);
63         SUnitMap[N] = NodeSUnit;
64       } while (N->getNumOperands() &&
65                N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
66       std::reverse(NodeSUnit->FlaggedNodes.begin(),
67                    NodeSUnit->FlaggedNodes.end());
68     }
69     
70     // Scan down, adding this node and any flagged succs to FlaggedNodes if they
71     // have a user of the flag operand.
72     N = NI;
73     while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
74       SDOperand FlagVal(N, N->getNumValues()-1);
75       
76       // There are either zero or one users of the Flag result.
77       bool HasFlagUse = false;
78       for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 
79            UI != E; ++UI)
80         if (FlagVal.isOperand(*UI)) {
81           HasFlagUse = true;
82           NodeSUnit->FlaggedNodes.push_back(N);
83           SUnitMap[N] = NodeSUnit;
84           N = *UI;
85           break;
86         }
87       if (!HasFlagUse) break;
88     }
89     
90     // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
91     // Update the SUnit
92     NodeSUnit->Node = N;
93     SUnitMap[N] = NodeSUnit;
94     
95     // Compute the latency for the node.  We use the sum of the latencies for
96     // all nodes flagged together into this SUnit.
97     if (InstrItins.isEmpty()) {
98       // No latency information.
99       NodeSUnit->Latency = 1;
100     } else {
101       NodeSUnit->Latency = 0;
102       if (N->isTargetOpcode()) {
103         unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
104         InstrStage *S = InstrItins.begin(SchedClass);
105         InstrStage *E = InstrItins.end(SchedClass);
106         for (; S != E; ++S)
107           NodeSUnit->Latency += S->Cycles;
108       }
109       for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
110         SDNode *FNode = NodeSUnit->FlaggedNodes[i];
111         if (FNode->isTargetOpcode()) {
112           unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
113           InstrStage *S = InstrItins.begin(SchedClass);
114           InstrStage *E = InstrItins.end(SchedClass);
115           for (; S != E; ++S)
116             NodeSUnit->Latency += S->Cycles;
117         }
118       }
119     }
120   }
121   
122   // Pass 2: add the preds, succs, etc.
123   for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
124     SUnit *SU = &SUnits[su];
125     SDNode *MainNode = SU->Node;
126     
127     if (MainNode->isTargetOpcode()) {
128       unsigned Opc = MainNode->getTargetOpcode();
129       for (unsigned i = 0, ee = TII->getNumOperands(Opc); i != ee; ++i) {
130         if (TII->getOperandConstraint(Opc, i,
131                                       TargetInstrInfo::TIED_TO) != -1) {
132           SU->isTwoAddress = true;
133           break;
134         }
135       }
136       if (TII->isCommutableInstr(Opc))
137         SU->isCommutable = true;
138     }
139     
140     // Find all predecessors and successors of the group.
141     // Temporarily add N to make code simpler.
142     SU->FlaggedNodes.push_back(MainNode);
143     
144     for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
145       SDNode *N = SU->FlaggedNodes[n];
146       
147       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
148         SDNode *OpN = N->getOperand(i).Val;
149         if (isPassiveNode(OpN)) continue;   // Not scheduled.
150         SUnit *OpSU = SUnitMap[OpN];
151         assert(OpSU && "Node has no SUnit!");
152         if (OpSU == SU) continue;           // In the same group.
153
154         MVT::ValueType OpVT = N->getOperand(i).getValueType();
155         assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
156         bool isChain = OpVT == MVT::Other;
157         
158         if (SU->addPred(OpSU, isChain)) {
159           if (!isChain) {
160             SU->NumPreds++;
161             SU->NumPredsLeft++;
162           } else {
163             SU->NumChainPredsLeft++;
164           }
165         }
166         if (OpSU->addSucc(SU, isChain)) {
167           if (!isChain) {
168             OpSU->NumSuccs++;
169             OpSU->NumSuccsLeft++;
170           } else {
171             OpSU->NumChainSuccsLeft++;
172           }
173         }
174       }
175     }
176     
177     // Remove MainNode from FlaggedNodes again.
178     SU->FlaggedNodes.pop_back();
179   }
180   
181   return;
182 }
183
184 static void CalculateDepths(SUnit &SU, unsigned Depth) {
185   if (SU.Depth == 0 || Depth > SU.Depth) {
186     SU.Depth = Depth;
187     for (SUnit::succ_iterator I = SU.Succs.begin(), E = SU.Succs.end();
188          I != E; ++I)
189       CalculateDepths(*I->first, Depth+1);
190   }
191 }
192
193 void ScheduleDAG::CalculateDepths() {
194   SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
195   ::CalculateDepths(*Entry, 0U);
196   for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
197     if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
198       ::CalculateDepths(SUnits[i], 0U);
199     }
200 }
201
202 static void CalculateHeights(SUnit &SU, unsigned Height) {
203   if (SU.Height == 0 || Height > SU.Height) {
204     SU.Height = Height;
205     for (SUnit::pred_iterator I = SU.Preds.begin(), E = SU.Preds.end();
206          I != E; ++I)
207       CalculateHeights(*I->first, Height+1);
208   }
209 }
210 void ScheduleDAG::CalculateHeights() {
211   SUnit *Root = SUnitMap[DAG.getRoot().Val];
212   ::CalculateHeights(*Root, 0U);
213 }
214
215 /// CountResults - The results of target nodes have register or immediate
216 /// operands first, then an optional chain, and optional flag operands (which do
217 /// not go into the machine instrs.)
218 unsigned ScheduleDAG::CountResults(SDNode *Node) {
219   unsigned N = Node->getNumValues();
220   while (N && Node->getValueType(N - 1) == MVT::Flag)
221     --N;
222   if (N && Node->getValueType(N - 1) == MVT::Other)
223     --N;    // Skip over chain result.
224   return N;
225 }
226
227 /// CountOperands  The inputs to target nodes have any actual inputs first,
228 /// followed by an optional chain operand, then flag operands.  Compute the
229 /// number of actual operands that  will go into the machine instr.
230 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
231   unsigned N = Node->getNumOperands();
232   while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
233     --N;
234   if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
235     --N; // Ignore chain if it exists.
236   return N;
237 }
238
239 static const TargetRegisterClass *getInstrOperandRegClass(
240         const MRegisterInfo *MRI, 
241         const TargetInstrInfo *TII,
242         const TargetInstrDescriptor *II,
243         unsigned Op) {
244   if (Op >= II->numOperands) {
245     assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
246     return NULL;
247   }
248   const TargetOperandInfo &toi = II->OpInfo[Op];
249   return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
250          ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
251 }
252
253 static unsigned CreateVirtualRegisters(const MRegisterInfo *MRI,
254                                        MachineInstr *MI,
255                                        unsigned NumResults,
256                                        SSARegMap *RegMap,
257                                        const TargetInstrInfo *TII,
258                                        const TargetInstrDescriptor &II) {
259   // Create the result registers for this node and add the result regs to
260   // the machine instruction.
261   unsigned ResultReg =
262     RegMap->createVirtualRegister(getInstrOperandRegClass(MRI, TII, &II, 0));
263   MI->addRegOperand(ResultReg, true);
264   for (unsigned i = 1; i != NumResults; ++i) {
265     const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
266     assert(RC && "Isn't a register operand!");
267     MI->addRegOperand(RegMap->createVirtualRegister(RC), true);
268   }
269   return ResultReg;
270 }
271
272 /// getVR - Return the virtual register corresponding to the specified result
273 /// of the specified node.
274 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
275   std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
276   assert(I != VRBaseMap.end() && "Node emitted out of order - late");
277   return I->second + Op.ResNo;
278 }
279
280
281 /// AddOperand - Add the specified operand to the specified machine instr.  II
282 /// specifies the instruction information for the node, and IIOpNum is the
283 /// operand number (in the II) that we are adding. IIOpNum and II are used for 
284 /// assertions only.
285 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
286                              unsigned IIOpNum,
287                              const TargetInstrDescriptor *II,
288                              std::map<SDNode*, unsigned> &VRBaseMap) {
289   if (Op.isTargetOpcode()) {
290     // Note that this case is redundant with the final else block, but we
291     // include it because it is the most common and it makes the logic
292     // simpler here.
293     assert(Op.getValueType() != MVT::Other &&
294            Op.getValueType() != MVT::Flag &&
295            "Chain and flag operands should occur at end of operand list!");
296     
297     // Get/emit the operand.
298     unsigned VReg = getVR(Op, VRBaseMap);
299     MI->addRegOperand(VReg, false);
300     
301     // Verify that it is right.
302     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
303     if (II) {
304       const TargetRegisterClass *RC =
305                           getInstrOperandRegClass(MRI, TII, II, IIOpNum);
306       assert(RC && "Don't have operand info for this instruction!");
307       assert(RegMap->getRegClass(VReg) == RC &&
308              "Register class of operand and regclass of use don't agree!");
309     }
310   } else if (ConstantSDNode *C =
311              dyn_cast<ConstantSDNode>(Op)) {
312     MI->addImmOperand(C->getValue());
313   } else if (RegisterSDNode*R =
314              dyn_cast<RegisterSDNode>(Op)) {
315     MI->addRegOperand(R->getReg(), false);
316   } else if (GlobalAddressSDNode *TGA =
317              dyn_cast<GlobalAddressSDNode>(Op)) {
318     MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
319   } else if (BasicBlockSDNode *BB =
320              dyn_cast<BasicBlockSDNode>(Op)) {
321     MI->addMachineBasicBlockOperand(BB->getBasicBlock());
322   } else if (FrameIndexSDNode *FI =
323              dyn_cast<FrameIndexSDNode>(Op)) {
324     MI->addFrameIndexOperand(FI->getIndex());
325   } else if (JumpTableSDNode *JT =
326              dyn_cast<JumpTableSDNode>(Op)) {
327     MI->addJumpTableIndexOperand(JT->getIndex());
328   } else if (ConstantPoolSDNode *CP = 
329              dyn_cast<ConstantPoolSDNode>(Op)) {
330     int Offset = CP->getOffset();
331     unsigned Align = CP->getAlignment();
332     const Type *Type = CP->getType();
333     // MachineConstantPool wants an explicit alignment.
334     if (Align == 0) {
335       if (Type == Type::DoubleTy)
336         Align = 3;  // always 8-byte align doubles.
337       else {
338         Align = TM.getTargetData()->getTypeAlignmentShift(Type);
339         if (Align == 0) {
340           // Alignment of packed types.  FIXME!
341           Align = TM.getTargetData()->getTypeSize(Type);
342           Align = Log2_64(Align);
343         }
344       }
345     }
346     
347     unsigned Idx;
348     if (CP->isMachineConstantPoolEntry())
349       Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
350     else
351       Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
352     MI->addConstantPoolIndexOperand(Idx, Offset);
353   } else if (ExternalSymbolSDNode *ES = 
354              dyn_cast<ExternalSymbolSDNode>(Op)) {
355     MI->addExternalSymbolOperand(ES->getSymbol());
356   } else {
357     assert(Op.getValueType() != MVT::Other &&
358            Op.getValueType() != MVT::Flag &&
359            "Chain and flag operands should occur at end of operand list!");
360     unsigned VReg = getVR(Op, VRBaseMap);
361     MI->addRegOperand(VReg, false);
362     
363     // Verify that it is right.
364     assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
365     if (II) {
366       const TargetRegisterClass *RC =
367                             getInstrOperandRegClass(MRI, TII, II, IIOpNum);
368       assert(RC && "Don't have operand info for this instruction!");
369       assert(RegMap->getRegClass(VReg) == RC &&
370              "Register class of operand and regclass of use don't agree!");
371     }
372   }
373   
374 }
375
376
377 /// EmitNode - Generate machine code for an node and needed dependencies.
378 ///
379 void ScheduleDAG::EmitNode(SDNode *Node, 
380                            std::map<SDNode*, unsigned> &VRBaseMap) {
381   unsigned VRBase = 0;                 // First virtual register for node
382   
383   // If machine instruction
384   if (Node->isTargetOpcode()) {
385     unsigned Opc = Node->getTargetOpcode();
386     const TargetInstrDescriptor &II = TII->get(Opc);
387
388     unsigned NumResults = CountResults(Node);
389     unsigned NodeOperands = CountOperands(Node);
390     unsigned NumMIOperands = NodeOperands + NumResults;
391 #ifndef NDEBUG
392     assert((unsigned(II.numOperands) == NumMIOperands ||
393             (II.Flags & M_VARIABLE_OPS)) &&
394            "#operands for dag node doesn't match .td file!"); 
395 #endif
396
397     // Create the new machine instruction.
398     MachineInstr *MI = new MachineInstr(Opc, NumMIOperands);
399     
400     // Add result register values for things that are defined by this
401     // instruction.
402     
403     // If the node is only used by a CopyToReg and the dest reg is a vreg, use
404     // the CopyToReg'd destination register instead of creating a new vreg.
405     if (NumResults == 1) {
406       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
407            UI != E; ++UI) {
408         SDNode *Use = *UI;
409         if (Use->getOpcode() == ISD::CopyToReg && 
410             Use->getOperand(2).Val == Node) {
411           unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
412           if (MRegisterInfo::isVirtualRegister(Reg)) {
413             VRBase = Reg;
414             MI->addRegOperand(Reg, true);
415             break;
416           }
417         }
418       }
419     }
420     
421     // Otherwise, create new virtual registers.
422     if (NumResults && VRBase == 0)
423       VRBase = CreateVirtualRegisters(MRI, MI, NumResults, RegMap, TII, II);
424     
425     // Emit all of the actual operands of this instruction, adding them to the
426     // instruction as appropriate.
427     for (unsigned i = 0; i != NodeOperands; ++i)
428       AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
429
430     // Commute node if it has been determined to be profitable.
431     if (CommuteSet.count(Node)) {
432       MachineInstr *NewMI = TII->commuteInstruction(MI);
433       if (NewMI == 0)
434         DEBUG(std::cerr << "Sched: COMMUTING FAILED!\n");
435       else {
436         DEBUG(std::cerr << "Sched: COMMUTED TO: " << *NewMI);
437         if (MI != NewMI) {
438           delete MI;
439           MI = NewMI;
440         }
441       }
442     }
443
444     // Now that we have emitted all operands, emit this instruction itself.
445     if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
446       BB->insert(BB->end(), MI);
447     } else {
448       // Insert this instruction into the end of the basic block, potentially
449       // taking some custom action.
450       BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
451     }
452   } else {
453     switch (Node->getOpcode()) {
454     default:
455 #ifndef NDEBUG
456       Node->dump();
457 #endif
458       assert(0 && "This target-independent node should have been selected!");
459     case ISD::EntryToken: // fall thru
460     case ISD::TokenFactor:
461       break;
462     case ISD::CopyToReg: {
463       unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
464       unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
465       if (InReg != DestReg)   // Coalesced away the copy?
466         MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
467                           RegMap->getRegClass(InReg));
468       break;
469     }
470     case ISD::CopyFromReg: {
471       unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
472       if (MRegisterInfo::isVirtualRegister(SrcReg)) {
473         VRBase = SrcReg;  // Just use the input register directly!
474         break;
475       }
476
477       // If the node is only used by a CopyToReg and the dest reg is a vreg, use
478       // the CopyToReg'd destination register instead of creating a new vreg.
479       for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
480            UI != E; ++UI) {
481         SDNode *Use = *UI;
482         if (Use->getOpcode() == ISD::CopyToReg && 
483             Use->getOperand(2).Val == Node) {
484           unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
485           if (MRegisterInfo::isVirtualRegister(DestReg)) {
486             VRBase = DestReg;
487             break;
488           }
489         }
490       }
491
492       // Figure out the register class to create for the destreg.
493       const TargetRegisterClass *TRC = 0;
494       if (VRBase) {
495         TRC = RegMap->getRegClass(VRBase);
496       } else {
497
498         // Pick the register class of the right type that contains this physreg.
499         for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
500              E = MRI->regclass_end(); I != E; ++I)
501           if ((*I)->hasType(Node->getValueType(0)) &&
502               (*I)->contains(SrcReg)) {
503             TRC = *I;
504             break;
505           }
506         assert(TRC && "Couldn't find register class for reg copy!");
507       
508         // Create the reg, emit the copy.
509         VRBase = RegMap->createVirtualRegister(TRC);
510       }
511       MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
512       break;
513     }
514     case ISD::INLINEASM: {
515       unsigned NumOps = Node->getNumOperands();
516       if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
517         --NumOps;  // Ignore the flag operand.
518       
519       // Create the inline asm machine instruction.
520       MachineInstr *MI =
521         new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
522
523       // Add the asm string as an external symbol operand.
524       const char *AsmStr =
525         cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
526       MI->addExternalSymbolOperand(AsmStr);
527       
528       // Add all of the operand registers to the instruction.
529       for (unsigned i = 2; i != NumOps;) {
530         unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
531         unsigned NumVals = Flags >> 3;
532         
533         MI->addImmOperand(Flags);
534         ++i;  // Skip the ID value.
535         
536         switch (Flags & 7) {
537         default: assert(0 && "Bad flags!");
538         case 1:  // Use of register.
539           for (; NumVals; --NumVals, ++i) {
540             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
541             MI->addRegOperand(Reg, false);
542           }
543           break;
544         case 2:   // Def of register.
545           for (; NumVals; --NumVals, ++i) {
546             unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
547             MI->addRegOperand(Reg, true);
548           }
549           break;
550         case 3: { // Immediate.
551           assert(NumVals == 1 && "Unknown immediate value!");
552           if (ConstantSDNode *CS=dyn_cast<ConstantSDNode>(Node->getOperand(i))){
553             MI->addImmOperand(CS->getValue());
554           } else {
555             GlobalAddressSDNode *GA = 
556               cast<GlobalAddressSDNode>(Node->getOperand(i));
557             MI->addGlobalAddressOperand(GA->getGlobal(), GA->getOffset());
558           }
559           ++i;
560           break;
561         }
562         case 4:  // Addressing mode.
563           // The addressing mode has been selected, just add all of the
564           // operands to the machine instruction.
565           for (; NumVals; --NumVals, ++i)
566             AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
567           break;
568         }
569       }
570       break;
571     }
572     }
573   }
574
575   assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
576   VRBaseMap[Node] = VRBase;
577 }
578
579 void ScheduleDAG::EmitNoop() {
580   TII->insertNoop(*BB, BB->end());
581 }
582
583 /// EmitSchedule - Emit the machine code in scheduled order.
584 void ScheduleDAG::EmitSchedule() {
585   // If this is the first basic block in the function, and if it has live ins
586   // that need to be copied into vregs, emit the copies into the top of the
587   // block before emitting the code for the block.
588   MachineFunction &MF = DAG.getMachineFunction();
589   if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
590     for (MachineFunction::livein_iterator LI = MF.livein_begin(),
591          E = MF.livein_end(); LI != E; ++LI)
592       if (LI->second)
593         MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
594                           LI->first, RegMap->getRegClass(LI->second));
595   }
596   
597   
598   // Finally, emit the code for all of the scheduled instructions.
599   std::map<SDNode*, unsigned> VRBaseMap;
600   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
601     if (SUnit *SU = Sequence[i]) {
602       for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
603         EmitNode(SU->FlaggedNodes[j], VRBaseMap);
604       EmitNode(SU->Node, VRBaseMap);
605     } else {
606       // Null SUnit* is a noop.
607       EmitNoop();
608     }
609   }
610 }
611
612 /// dump - dump the schedule.
613 void ScheduleDAG::dumpSchedule() const {
614   for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
615     if (SUnit *SU = Sequence[i])
616       SU->dump(&DAG);
617     else
618       std::cerr << "**** NOOP ****\n";
619   }
620 }
621
622
623 /// Run - perform scheduling.
624 ///
625 MachineBasicBlock *ScheduleDAG::Run() {
626   TII = TM.getInstrInfo();
627   MRI = TM.getRegisterInfo();
628   RegMap = BB->getParent()->getSSARegMap();
629   ConstPool = BB->getParent()->getConstantPool();
630
631   Schedule();
632   return BB;
633 }
634
635 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
636 /// a group of nodes flagged together.
637 void SUnit::dump(const SelectionDAG *G) const {
638   std::cerr << "SU(" << NodeNum << "): ";
639   Node->dump(G);
640   std::cerr << "\n";
641   if (FlaggedNodes.size() != 0) {
642     for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
643       std::cerr << "    ";
644       FlaggedNodes[i]->dump(G);
645       std::cerr << "\n";
646     }
647   }
648 }
649
650 void SUnit::dumpAll(const SelectionDAG *G) const {
651   dump(G);
652
653   std::cerr << "  # preds left       : " << NumPredsLeft << "\n";
654   std::cerr << "  # succs left       : " << NumSuccsLeft << "\n";
655   std::cerr << "  # chain preds left : " << NumChainPredsLeft << "\n";
656   std::cerr << "  # chain succs left : " << NumChainSuccsLeft << "\n";
657   std::cerr << "  Latency            : " << Latency << "\n";
658   std::cerr << "  Depth              : " << Depth << "\n";
659   std::cerr << "  Height             : " << Height << "\n";
660
661   if (Preds.size() != 0) {
662     std::cerr << "  Predecessors:\n";
663     for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
664          I != E; ++I) {
665       if (I->second)
666         std::cerr << "   ch  #";
667       else
668         std::cerr << "   val #";
669       std::cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
670     }
671   }
672   if (Succs.size() != 0) {
673     std::cerr << "  Successors:\n";
674     for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
675          I != E; ++I) {
676       if (I->second)
677         std::cerr << "   ch  #";
678       else
679         std::cerr << "   val #";
680       std::cerr << I->first << " - SU(" << I->first->NodeNum << ")\n";
681     }
682   }
683   std::cerr << "\n";
684 }