1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
14 //===----------------------------------------------------------------------===//
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/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
33 STATISTIC(NumCommutes, "Number of instructions commuted");
37 SchedLiveInCopies("schedule-livein-copies",
38 cl::desc("Schedule copies of livein registers"),
42 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
43 const TargetMachine &tm)
44 : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
45 TII = TM.getInstrInfo();
46 MF = &DAG.getMachineFunction();
47 TRI = TM.getRegisterInfo();
48 ConstPool = BB->getParent()->getConstantPool();
51 /// CheckForPhysRegDependency - Check if the dependency between def and use of
52 /// a specified operand is a physical register dependency. If so, returns the
53 /// register and the cost of copying the register.
54 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
55 const TargetRegisterInfo *TRI,
56 const TargetInstrInfo *TII,
57 unsigned &PhysReg, int &Cost) {
58 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
61 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
62 if (TargetRegisterInfo::isVirtualRegister(Reg))
65 unsigned ResNo = Use->getOperand(2).ResNo;
66 if (Def->isTargetOpcode()) {
67 const TargetInstrDesc &II = TII->get(Def->getTargetOpcode());
68 if (ResNo >= II.getNumDefs() &&
69 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) {
71 const TargetRegisterClass *RC =
72 TRI->getPhysicalRegisterRegClass(Reg, Def->getValueType(ResNo));
73 Cost = RC->getCopyCost();
78 SUnit *ScheduleDAG::Clone(SUnit *Old) {
79 SUnit *SU = NewSUnit(Old->Node);
80 SU->FlaggedNodes = Old->FlaggedNodes;
81 SU->InstanceNo = SUnitMap[Old->Node].size();
82 SU->Latency = Old->Latency;
83 SU->isTwoAddress = Old->isTwoAddress;
84 SU->isCommutable = Old->isCommutable;
85 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
86 SUnitMap[Old->Node].push_back(SU);
91 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
92 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
93 /// together nodes with a single SUnit.
94 void ScheduleDAG::BuildSchedUnits() {
95 // Reserve entries in the vector for each of the SUnits we are creating. This
96 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
98 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
100 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
101 E = DAG.allnodes_end(); NI != E; ++NI) {
102 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
105 // If this node has already been processed, stop now.
106 if (SUnitMap[NI].size()) continue;
108 SUnit *NodeSUnit = NewSUnit(NI);
110 // See if anything is flagged to this node, if so, add them to flagged
111 // nodes. Nodes can have at most one flag input and one flag output. Flags
112 // are required the be the last operand and result of a node.
114 // Scan up, adding flagged preds to FlaggedNodes.
116 if (N->getNumOperands() &&
117 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
119 N = N->getOperand(N->getNumOperands()-1).Val;
120 NodeSUnit->FlaggedNodes.push_back(N);
121 SUnitMap[N].push_back(NodeSUnit);
122 } while (N->getNumOperands() &&
123 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
124 std::reverse(NodeSUnit->FlaggedNodes.begin(),
125 NodeSUnit->FlaggedNodes.end());
128 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
129 // have a user of the flag operand.
131 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
132 SDOperand FlagVal(N, N->getNumValues()-1);
134 // There are either zero or one users of the Flag result.
135 bool HasFlagUse = false;
136 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
138 if (FlagVal.isOperandOf(*UI)) {
140 NodeSUnit->FlaggedNodes.push_back(N);
141 SUnitMap[N].push_back(NodeSUnit);
145 if (!HasFlagUse) break;
148 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
151 SUnitMap[N].push_back(NodeSUnit);
153 ComputeLatency(NodeSUnit);
156 // Pass 2: add the preds, succs, etc.
157 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
158 SUnit *SU = &SUnits[su];
159 SDNode *MainNode = SU->Node;
161 if (MainNode->isTargetOpcode()) {
162 unsigned Opc = MainNode->getTargetOpcode();
163 const TargetInstrDesc &TID = TII->get(Opc);
164 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
165 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
166 SU->isTwoAddress = true;
170 if (TID.isCommutable())
171 SU->isCommutable = true;
174 // Find all predecessors and successors of the group.
175 // Temporarily add N to make code simpler.
176 SU->FlaggedNodes.push_back(MainNode);
178 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
179 SDNode *N = SU->FlaggedNodes[n];
180 if (N->isTargetOpcode() &&
181 TII->get(N->getTargetOpcode()).getImplicitDefs() &&
182 CountResults(N) > TII->get(N->getTargetOpcode()).getNumDefs())
183 SU->hasPhysRegDefs = true;
185 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
186 SDNode *OpN = N->getOperand(i).Val;
187 if (isPassiveNode(OpN)) continue; // Not scheduled.
188 SUnit *OpSU = SUnitMap[OpN].front();
189 assert(OpSU && "Node has no SUnit!");
190 if (OpSU == SU) continue; // In the same group.
192 MVT::ValueType OpVT = N->getOperand(i).getValueType();
193 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
194 bool isChain = OpVT == MVT::Other;
196 unsigned PhysReg = 0;
198 // Determine if this is a physical register dependency.
199 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
200 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
204 // Remove MainNode from FlaggedNodes again.
205 SU->FlaggedNodes.pop_back();
211 void ScheduleDAG::ComputeLatency(SUnit *SU) {
212 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
214 // Compute the latency for the node. We use the sum of the latencies for
215 // all nodes flagged together into this SUnit.
216 if (InstrItins.isEmpty()) {
217 // No latency information.
221 if (SU->Node->isTargetOpcode()) {
222 unsigned SchedClass =
223 TII->get(SU->Node->getTargetOpcode()).getSchedClass();
224 InstrStage *S = InstrItins.begin(SchedClass);
225 InstrStage *E = InstrItins.end(SchedClass);
227 SU->Latency += S->Cycles;
229 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
230 SDNode *FNode = SU->FlaggedNodes[i];
231 if (FNode->isTargetOpcode()) {
232 unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
233 InstrStage *S = InstrItins.begin(SchedClass);
234 InstrStage *E = InstrItins.end(SchedClass);
236 SU->Latency += S->Cycles;
242 /// CalculateDepths - compute depths using algorithms for the longest
244 void ScheduleDAG::CalculateDepths() {
245 unsigned DAGSize = SUnits.size();
246 std::vector<unsigned> InDegree(DAGSize);
247 std::vector<SUnit*> WorkList;
248 WorkList.reserve(DAGSize);
250 // Initialize the data structures
251 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
252 SUnit *SU = &SUnits[i];
253 int NodeNum = SU->NodeNum;
254 unsigned Degree = SU->Preds.size();
255 InDegree[NodeNum] = Degree;
258 // Is it a node without dependencies?
260 assert(SU->Preds.empty() && "SUnit should have no predecessors");
261 // Collect leaf nodes
262 WorkList.push_back(SU);
266 // Process nodes in the topological order
267 while (!WorkList.empty()) {
268 SUnit *SU = WorkList.back();
270 unsigned &SUDepth = SU->Depth;
272 // Use dynamic programming:
273 // When current node is being processed, all of its dependencies
274 // are already processed.
275 // So, just iterate over all predecessors and take the longest path
276 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
278 unsigned PredDepth = I->Dep->Depth;
279 if (PredDepth+1 > SUDepth) {
280 SUDepth = PredDepth + 1;
284 // Update InDegrees of all nodes depending on current SUnit
285 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
288 if (!--InDegree[SU->NodeNum])
289 // If all dependencies of the node are processed already,
290 // then the longest path for the node can be computed now
291 WorkList.push_back(SU);
296 /// CalculateHeights - compute heights using algorithms for the longest
298 void ScheduleDAG::CalculateHeights() {
299 unsigned DAGSize = SUnits.size();
300 std::vector<unsigned> InDegree(DAGSize);
301 std::vector<SUnit*> WorkList;
302 WorkList.reserve(DAGSize);
304 // Initialize the data structures
305 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
306 SUnit *SU = &SUnits[i];
307 int NodeNum = SU->NodeNum;
308 unsigned Degree = SU->Succs.size();
309 InDegree[NodeNum] = Degree;
312 // Is it a node without dependencies?
314 assert(SU->Succs.empty() && "Something wrong");
315 assert(WorkList.empty() && "Should be empty");
316 // Collect leaf nodes
317 WorkList.push_back(SU);
321 // Process nodes in the topological order
322 while (!WorkList.empty()) {
323 SUnit *SU = WorkList.back();
325 unsigned &SUHeight = SU->Height;
327 // Use dynamic programming:
328 // When current node is being processed, all of its dependencies
329 // are already processed.
330 // So, just iterate over all successors and take the longest path
331 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
333 unsigned SuccHeight = I->Dep->Height;
334 if (SuccHeight+1 > SUHeight) {
335 SUHeight = SuccHeight + 1;
339 // Update InDegrees of all nodes depending on current SUnit
340 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
343 if (!--InDegree[SU->NodeNum])
344 // If all dependencies of the node are processed already,
345 // then the longest path for the node can be computed now
346 WorkList.push_back(SU);
351 /// CountResults - The results of target nodes have register or immediate
352 /// operands first, then an optional chain, and optional flag operands (which do
353 /// not go into the resulting MachineInstr).
354 unsigned ScheduleDAG::CountResults(SDNode *Node) {
355 unsigned N = Node->getNumValues();
356 while (N && Node->getValueType(N - 1) == MVT::Flag)
358 if (N && Node->getValueType(N - 1) == MVT::Other)
359 --N; // Skip over chain result.
363 /// CountOperands - The inputs to target nodes have any actual inputs first,
364 /// followed by special operands that describe memory references, then an
365 /// optional chain operand, then flag operands. Compute the number of
366 /// actual operands that will go into the resulting MachineInstr.
367 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
368 unsigned N = ComputeMemOperandsEnd(Node);
369 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
370 --N; // Ignore MemOperand nodes
374 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
376 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
377 unsigned N = Node->getNumOperands();
378 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
380 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
381 --N; // Ignore chain if it exists.
385 static const TargetRegisterClass *getInstrOperandRegClass(
386 const TargetRegisterInfo *TRI,
387 const TargetInstrInfo *TII,
388 const TargetInstrDesc &II,
390 if (Op >= II.getNumOperands()) {
391 assert(II.isVariadic() && "Invalid operand # of instruction");
394 if (II.OpInfo[Op].isLookupPtrRegClass())
395 return TII->getPointerRegClass();
396 return TRI->getRegClass(II.OpInfo[Op].RegClass);
399 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
400 unsigned InstanceNo, unsigned SrcReg,
401 DenseMap<SDOperand, unsigned> &VRBaseMap) {
403 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
404 // Just use the input register directly!
406 VRBaseMap.erase(SDOperand(Node, ResNo));
407 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
408 assert(isNew && "Node emitted out of order - early");
412 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
413 // the CopyToReg'd destination register instead of creating a new vreg.
414 bool MatchReg = true;
415 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
419 if (Use->getOpcode() == ISD::CopyToReg &&
420 Use->getOperand(2).Val == Node &&
421 Use->getOperand(2).ResNo == ResNo) {
422 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
423 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
426 } else if (DestReg != SrcReg)
429 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
430 SDOperand Op = Use->getOperand(i);
431 if (Op.Val != Node || Op.ResNo != ResNo)
433 MVT::ValueType VT = Node->getValueType(Op.ResNo);
434 if (VT != MVT::Other && VT != MVT::Flag)
443 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
444 SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, Node->getValueType(ResNo));
446 // Figure out the register class to create for the destreg.
448 DstRC = MRI.getRegClass(VRBase);
450 DstRC = DAG.getTargetLoweringInfo()
451 .getRegClassFor(Node->getValueType(ResNo));
454 // If all uses are reading from the src physical register and copying the
455 // register is either impossible or very expensive, then don't create a copy.
456 if (MatchReg && SrcRC->getCopyCost() < 0) {
459 // Create the reg, emit the copy.
460 VRBase = MRI.createVirtualRegister(DstRC);
461 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
465 VRBaseMap.erase(SDOperand(Node, ResNo));
466 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
467 assert(isNew && "Node emitted out of order - early");
470 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
471 const TargetInstrDesc &II,
472 DenseMap<SDOperand, unsigned> &VRBaseMap) {
473 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
474 // If the specific node value is only used by a CopyToReg and the dest reg
475 // is a vreg, use the CopyToReg'd destination register instead of creating
478 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
481 if (Use->getOpcode() == ISD::CopyToReg &&
482 Use->getOperand(2).Val == Node &&
483 Use->getOperand(2).ResNo == i) {
484 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
485 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
487 MI->addOperand(MachineOperand::CreateReg(Reg, true));
493 // Create the result registers for this node and add the result regs to
494 // the machine instruction.
496 const TargetRegisterClass *RC;
497 if (Node->getTargetOpcode() == TargetInstrInfo::IMPLICIT_DEF)
498 // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
499 // does not include operand register class info.
500 RC = DAG.getTargetLoweringInfo().getRegClassFor(Node->getValueType(0));
502 RC = getInstrOperandRegClass(TRI, TII, II, i);
503 assert(RC && "Isn't a register operand!");
504 VRBase = MRI.createVirtualRegister(RC);
505 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
508 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
509 assert(isNew && "Node emitted out of order - early");
513 /// getVR - Return the virtual register corresponding to the specified result
514 /// of the specified node.
515 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
516 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
517 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
522 /// AddOperand - Add the specified operand to the specified machine instr. II
523 /// specifies the instruction information for the node, and IIOpNum is the
524 /// operand number (in the II) that we are adding. IIOpNum and II are used for
526 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
528 const TargetInstrDesc *II,
529 DenseMap<SDOperand, unsigned> &VRBaseMap) {
530 if (Op.isTargetOpcode()) {
531 // Note that this case is redundant with the final else block, but we
532 // include it because it is the most common and it makes the logic
534 assert(Op.getValueType() != MVT::Other &&
535 Op.getValueType() != MVT::Flag &&
536 "Chain and flag operands should occur at end of operand list!");
538 // Get/emit the operand.
539 unsigned VReg = getVR(Op, VRBaseMap);
540 const TargetInstrDesc &TID = MI->getDesc();
541 bool isOptDef = (IIOpNum < TID.getNumOperands())
542 ? (TID.OpInfo[IIOpNum].isOptionalDef()) : false;
543 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
545 // Verify that it is right.
546 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
549 // There may be no register class for this operand if it is a variadic
550 // argument (RC will be NULL in this case). In this case, we just assume
551 // the regclass is ok.
552 const TargetRegisterClass *RC =
553 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
554 assert((RC || II->isVariadic()) && "Expected reg class info!");
555 const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
556 if (RC && VRC != RC) {
557 cerr << "Register class of operand and regclass of use don't agree!\n";
558 cerr << "Operand = " << IIOpNum << "\n";
559 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
560 cerr << "MI = "; MI->print(cerr);
561 cerr << "VReg = " << VReg << "\n";
562 cerr << "VReg RegClass size = " << VRC->getSize()
563 << ", align = " << VRC->getAlignment() << "\n";
564 cerr << "Expected RegClass size = " << RC->getSize()
565 << ", align = " << RC->getAlignment() << "\n";
566 cerr << "Fatal error, aborting.\n";
571 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
572 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
573 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
574 const Type *FType = MVT::getTypeForValueType(Op.getValueType());
575 ConstantFP *CFP = ConstantFP::get(FType, F->getValueAPF());
576 MI->addOperand(MachineOperand::CreateFPImm(CFP));
577 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
578 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
579 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
580 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
581 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
582 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
583 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
584 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
585 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
586 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
587 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
588 int Offset = CP->getOffset();
589 unsigned Align = CP->getAlignment();
590 const Type *Type = CP->getType();
591 // MachineConstantPool wants an explicit alignment.
593 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
595 // Alignment of vector types. FIXME!
596 Align = TM.getTargetData()->getABITypeSize(Type);
597 Align = Log2_64(Align);
602 if (CP->isMachineConstantPoolEntry())
603 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
605 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
606 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
607 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
608 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
610 assert(Op.getValueType() != MVT::Other &&
611 Op.getValueType() != MVT::Flag &&
612 "Chain and flag operands should occur at end of operand list!");
613 unsigned VReg = getVR(Op, VRBaseMap);
614 MI->addOperand(MachineOperand::CreateReg(VReg, false));
616 // Verify that it is right. Note that the reg class of the physreg and the
617 // vreg don't necessarily need to match, but the target copy insertion has
618 // to be able to handle it. This handles things like copies from ST(0) to
619 // an FP vreg on x86.
620 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
621 if (II && !II->isVariadic()) {
622 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
623 "Don't have operand info for this instruction!");
629 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MemOperand &MO) {
630 MI->addMemOperand(MO);
633 // Returns the Register Class of a subregister
634 static const TargetRegisterClass *getSubRegisterRegClass(
635 const TargetRegisterClass *TRC,
637 // Pick the register class of the subregister
638 TargetRegisterInfo::regclass_iterator I =
639 TRC->subregclasses_begin() + SubIdx-1;
640 assert(I < TRC->subregclasses_end() &&
641 "Invalid subregister index for register class");
645 static const TargetRegisterClass *getSuperregRegisterClass(
646 const TargetRegisterClass *TRC,
649 // Pick the register class of the superegister for this type
650 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
651 E = TRC->superregclasses_end(); I != E; ++I)
652 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
654 assert(false && "Couldn't find the register class");
658 /// EmitSubregNode - Generate machine code for subreg nodes.
660 void ScheduleDAG::EmitSubregNode(SDNode *Node,
661 DenseMap<SDOperand, unsigned> &VRBaseMap) {
663 unsigned Opc = Node->getTargetOpcode();
664 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
665 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
666 // the CopyToReg'd destination register instead of creating a new vreg.
667 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
670 if (Use->getOpcode() == ISD::CopyToReg &&
671 Use->getOperand(2).Val == Node) {
672 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
673 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
680 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
682 // TODO: If the node is a use of a CopyFromReg from a physical register
683 // fold the extract into the copy now
685 // Create the extract_subreg machine instruction.
687 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
689 // Figure out the register class to create for the destreg.
690 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
691 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
692 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
695 // Grab the destination register
696 const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
697 assert(SRC && DRC && SRC == DRC &&
698 "Source subregister and destination must have the same class");
701 assert(SRC && "Couldn't find source register class");
702 VRBase = MRI.createVirtualRegister(SRC);
705 // Add def, source, and subreg index
706 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
707 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
708 MI->addOperand(MachineOperand::CreateImm(SubIdx));
710 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
711 SDOperand N0 = Node->getOperand(0);
712 SDOperand N1 = Node->getOperand(1);
713 SDOperand N2 = Node->getOperand(2);
714 unsigned SubReg = getVR(N1, VRBaseMap);
715 unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
717 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
718 // to allow coalescing in the allocator
720 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
721 // the CopyToReg'd destination register instead of creating a new vreg.
722 // If the CopyToReg'd destination register is physical, then fold the
723 // insert into the copy
724 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
727 if (Use->getOpcode() == ISD::CopyToReg &&
728 Use->getOperand(2).Val == Node) {
729 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
730 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
737 // Create the insert_subreg machine instruction.
739 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
741 // Figure out the register class to create for the destreg.
742 const TargetRegisterClass *TRC = 0;
744 TRC = MRI.getRegClass(VRBase);
746 TRC = getSuperregRegisterClass(MRI.getRegClass(SubReg), SubIdx,
747 Node->getValueType(0));
748 assert(TRC && "Couldn't determine register class for insert_subreg");
749 VRBase = MRI.createVirtualRegister(TRC); // Create the reg
752 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
754 // If N0 is a constant then it indicates the insert is being done
755 // into a target specific constant value, not a register.
756 if (const ConstantSDNode *SD = dyn_cast<ConstantSDNode>(N0))
757 MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
759 AddOperand(MI, N0, 0, 0, VRBaseMap);
760 // Add the subregster being inserted
761 AddOperand(MI, N1, 0, 0, VRBaseMap);
762 MI->addOperand(MachineOperand::CreateImm(SubIdx));
764 assert(0 && "Node is not a subreg insert or extract");
766 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
767 assert(isNew && "Node emitted out of order - early");
770 /// EmitNode - Generate machine code for an node and needed dependencies.
772 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
773 DenseMap<SDOperand, unsigned> &VRBaseMap) {
774 // If machine instruction
775 if (Node->isTargetOpcode()) {
776 unsigned Opc = Node->getTargetOpcode();
778 // Handle subreg insert/extract specially
779 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
780 Opc == TargetInstrInfo::INSERT_SUBREG) {
781 EmitSubregNode(Node, VRBaseMap);
785 const TargetInstrDesc &II = TII->get(Opc);
787 unsigned NumResults = CountResults(Node);
788 unsigned NodeOperands = CountOperands(Node);
789 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
790 unsigned NumMIOperands = NodeOperands + NumResults;
791 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
792 II.getImplicitDefs() != 0;
794 assert((II.getNumOperands() == NumMIOperands ||
795 HasPhysRegOuts || II.isVariadic()) &&
796 "#operands for dag node doesn't match .td file!");
799 // Create the new machine instruction.
800 MachineInstr *MI = new MachineInstr(II);
802 // Add result register values for things that are defined by this
805 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
807 // Emit all of the actual operands of this instruction, adding them to the
808 // instruction as appropriate.
809 for (unsigned i = 0; i != NodeOperands; ++i)
810 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
812 // Emit all of the memory operands of this instruction
813 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
814 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
816 // Commute node if it has been determined to be profitable.
817 if (CommuteSet.count(Node)) {
818 MachineInstr *NewMI = TII->commuteInstruction(MI);
820 DOUT << "Sched: COMMUTING FAILED!\n";
822 DOUT << "Sched: COMMUTED TO: " << *NewMI;
831 if (II.usesCustomDAGSchedInsertionHook())
832 // Insert this instruction into the basic block using a target
833 // specific inserter which may returns a new basic block.
834 BB = DAG.getTargetLoweringInfo().EmitInstrWithCustomInserter(MI, BB);
838 // Additional results must be an physical register def.
839 if (HasPhysRegOuts) {
840 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
841 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
842 if (Node->hasAnyUseOfValue(i))
843 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
847 switch (Node->getOpcode()) {
852 assert(0 && "This target-independent node should have been selected!");
853 case ISD::EntryToken: // fall thru
854 case ISD::TokenFactor:
859 case ISD::CopyToReg: {
861 SDOperand SrcVal = Node->getOperand(2);
862 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
863 SrcReg = R->getReg();
865 SrcReg = getVR(SrcVal, VRBaseMap);
867 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
868 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
871 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
872 // Get the register classes of the src/dst.
873 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
874 SrcTRC = MRI.getRegClass(SrcReg);
876 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
878 if (TargetRegisterInfo::isVirtualRegister(DestReg))
879 DstTRC = MRI.getRegClass(DestReg);
881 DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
882 Node->getOperand(1).getValueType());
883 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
886 case ISD::CopyFromReg: {
887 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
888 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
891 case ISD::INLINEASM: {
892 unsigned NumOps = Node->getNumOperands();
893 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
894 --NumOps; // Ignore the flag operand.
896 // Create the inline asm machine instruction.
898 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
900 // Add the asm string as an external symbol operand.
902 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
903 MI->addOperand(MachineOperand::CreateES(AsmStr));
905 // Add all of the operand registers to the instruction.
906 for (unsigned i = 2; i != NumOps;) {
907 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
908 unsigned NumVals = Flags >> 3;
910 MI->addOperand(MachineOperand::CreateImm(Flags));
911 ++i; // Skip the ID value.
914 default: assert(0 && "Bad flags!");
915 case 1: // Use of register.
916 for (; NumVals; --NumVals, ++i) {
917 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
918 MI->addOperand(MachineOperand::CreateReg(Reg, false));
921 case 2: // Def of register.
922 for (; NumVals; --NumVals, ++i) {
923 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
924 MI->addOperand(MachineOperand::CreateReg(Reg, true));
927 case 3: { // Immediate.
928 for (; NumVals; --NumVals, ++i) {
929 if (ConstantSDNode *CS =
930 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
931 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
932 } else if (GlobalAddressSDNode *GA =
933 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
934 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
937 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
938 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
943 case 4: // Addressing mode.
944 // The addressing mode has been selected, just add all of the
945 // operands to the machine instruction.
946 for (; NumVals; --NumVals, ++i)
947 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
957 void ScheduleDAG::EmitNoop() {
958 TII->insertNoop(*BB, BB->end());
961 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
962 DenseMap<SUnit*, unsigned> &VRBaseMap) {
963 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
965 if (I->isCtrl) continue; // ignore chain preds
967 // Copy to physical register.
968 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
969 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
970 // Find the destination physical register.
972 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
973 EE = SU->Succs.end(); II != EE; ++II) {
979 assert(I->Reg && "Unknown physical register!");
980 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
981 SU->CopyDstRC, SU->CopySrcRC);
983 // Copy from physical register.
984 assert(I->Reg && "Unknown physical register!");
985 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
986 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
987 assert(isNew && "Node emitted out of order - early");
988 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
989 SU->CopyDstRC, SU->CopySrcRC);
995 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
996 /// physical register has only a single copy use, then coalesced the copy
998 void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
999 MachineBasicBlock::iterator &InsertPos,
1000 unsigned VirtReg, unsigned PhysReg,
1001 const TargetRegisterClass *RC,
1002 DenseMap<MachineInstr*, unsigned> &CopyRegMap){
1003 unsigned NumUses = 0;
1004 MachineInstr *UseMI = NULL;
1005 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
1006 UE = MRI.use_end(); UI != UE; ++UI) {
1012 // If the number of uses is not one, or the use is not a move instruction,
1013 // don't coalesce. Also, only coalesce away a virtual register to virtual
1015 bool Coalesced = false;
1016 unsigned SrcReg, DstReg;
1018 TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
1019 TargetRegisterInfo::isVirtualRegister(DstReg)) {
1024 // Now find an ideal location to insert the copy.
1025 MachineBasicBlock::iterator Pos = InsertPos;
1026 while (Pos != MBB->begin()) {
1027 MachineInstr *PrevMI = prior(Pos);
1028 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
1029 // copyRegToReg might emit multiple instructions to do a copy.
1030 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
1031 if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
1032 // This is what the BB looks like right now:
1037 // We want to insert "r1025 = mov r1". Inserting this copy below the
1038 // move to r1024 makes it impossible for that move to be coalesced.
1045 break; // Woot! Found a good location.
1049 TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
1050 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
1052 if (&*InsertPos == UseMI) ++InsertPos;
1057 /// EmitLiveInCopies - If this is the first basic block in the function,
1058 /// and if it has live ins that need to be copied into vregs, emit the
1059 /// copies into the top of the block.
1060 void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
1061 DenseMap<MachineInstr*, unsigned> CopyRegMap;
1062 MachineBasicBlock::iterator InsertPos = MBB->begin();
1063 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1064 E = MRI.livein_end(); LI != E; ++LI)
1066 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1067 EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
1071 /// EmitSchedule - Emit the machine code in scheduled order.
1072 void ScheduleDAG::EmitSchedule() {
1073 bool isEntryBB = &MF->front() == BB;
1075 if (isEntryBB && !SchedLiveInCopies) {
1076 // If this is the first basic block in the function, and if it has live ins
1077 // that need to be copied into vregs, emit the copies into the top of the
1078 // block before emitting the code for the block.
1079 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1080 E = MRI.livein_end(); LI != E; ++LI)
1082 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1083 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1088 // Finally, emit the code for all of the scheduled instructions.
1089 DenseMap<SDOperand, unsigned> VRBaseMap;
1090 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1091 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1092 if (SUnit *SU = Sequence[i]) {
1093 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1094 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
1096 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
1098 EmitCrossRCCopy(SU, CopyVRBaseMap);
1100 // Null SUnit* is a noop.
1105 if (isEntryBB && SchedLiveInCopies)
1106 EmitLiveInCopies(MF->begin());
1109 /// dump - dump the schedule.
1110 void ScheduleDAG::dumpSchedule() const {
1111 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1112 if (SUnit *SU = Sequence[i])
1115 cerr << "**** NOOP ****\n";
1120 /// Run - perform scheduling.
1122 MachineBasicBlock *ScheduleDAG::Run() {
1127 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1128 /// a group of nodes flagged together.
1129 void SUnit::dump(const SelectionDAG *G) const {
1130 cerr << "SU(" << NodeNum << "): ";
1134 cerr << "CROSS RC COPY ";
1136 if (FlaggedNodes.size() != 0) {
1137 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1139 FlaggedNodes[i]->dump(G);
1145 void SUnit::dumpAll(const SelectionDAG *G) const {
1148 cerr << " # preds left : " << NumPredsLeft << "\n";
1149 cerr << " # succs left : " << NumSuccsLeft << "\n";
1150 cerr << " Latency : " << Latency << "\n";
1151 cerr << " Depth : " << Depth << "\n";
1152 cerr << " Height : " << Height << "\n";
1154 if (Preds.size() != 0) {
1155 cerr << " Predecessors:\n";
1156 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1162 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1168 if (Succs.size() != 0) {
1169 cerr << " Successors:\n";
1170 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1176 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";