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