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