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