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 the ScheduleDAG class, which is a base class used by
11 // scheduling implementation classes.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "pre-RA-sched"
16 #include "llvm/Type.h"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.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/ADT/Statistic.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
32 STATISTIC(NumCommutes, "Number of instructions commuted");
36 SchedLiveInCopies("schedule-livein-copies",
37 cl::desc("Schedule copies of livein registers"),
41 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
42 const TargetMachine &tm)
43 : DAG(dag), BB(bb), TM(tm), MRI(BB->getParent()->getRegInfo()) {
44 TII = TM.getInstrInfo();
45 MF = &DAG.getMachineFunction();
46 TRI = TM.getRegisterInfo();
47 TLI = &DAG.getTargetLoweringInfo();
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 *User, unsigned Op,
55 const TargetRegisterInfo *TRI,
56 const TargetInstrInfo *TII,
57 unsigned &PhysReg, int &Cost) {
58 if (Op != 2 || User->getOpcode() != ISD::CopyToReg)
61 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
62 if (TargetRegisterInfo::isVirtualRegister(Reg))
65 unsigned ResNo = User->getOperand(2).ResNo;
66 if (Def->isMachineOpcode()) {
67 const TargetInstrDesc &II = TII->get(Def->getMachineOpcode());
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->OrigNode = Old->OrigNode;
81 SU->FlaggedNodes = Old->FlaggedNodes;
82 SU->Latency = Old->Latency;
83 SU->isTwoAddress = Old->isTwoAddress;
84 SU->isCommutable = Old->isCommutable;
85 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
90 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
91 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
92 /// together nodes with a single SUnit.
93 void ScheduleDAG::BuildSchedUnits() {
94 // Reserve entries in the vector for each of the SUnits we are creating. This
95 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
97 SUnits.reserve(DAG.allnodes_size());
99 // During scheduling, the NodeId field of SDNode is used to map SDNodes
100 // to their associated SUnits by holding SUnits table indices. A value
101 // of -1 means the SDNode does not yet have an associated SUnit.
102 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
103 E = DAG.allnodes_end(); NI != E; ++NI)
106 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
107 E = DAG.allnodes_end(); NI != E; ++NI) {
108 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
111 // If this node has already been processed, stop now.
112 if (NI->getNodeId() != -1) continue;
114 SUnit *NodeSUnit = NewSUnit(NI);
116 // See if anything is flagged to this node, if so, add them to flagged
117 // nodes. Nodes can have at most one flag input and one flag output. Flags
118 // are required the be the last operand and result of a node.
120 // Scan up, adding flagged preds to FlaggedNodes.
122 if (N->getNumOperands() &&
123 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
125 N = N->getOperand(N->getNumOperands()-1).Val;
126 NodeSUnit->FlaggedNodes.push_back(N);
127 assert(N->getNodeId() == -1 && "Node already inserted!");
128 N->setNodeId(NodeSUnit->NodeNum);
129 } while (N->getNumOperands() &&
130 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
131 std::reverse(NodeSUnit->FlaggedNodes.begin(),
132 NodeSUnit->FlaggedNodes.end());
135 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
136 // have a user of the flag operand.
138 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
139 SDValue FlagVal(N, N->getNumValues()-1);
141 // There are either zero or one users of the Flag result.
142 bool HasFlagUse = false;
143 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
145 if (FlagVal.isOperandOf(*UI)) {
147 NodeSUnit->FlaggedNodes.push_back(N);
148 assert(N->getNodeId() == -1 && "Node already inserted!");
149 N->setNodeId(NodeSUnit->NodeNum);
153 if (!HasFlagUse) break;
156 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
159 assert(N->getNodeId() == -1 && "Node already inserted!");
160 N->setNodeId(NodeSUnit->NodeNum);
162 ComputeLatency(NodeSUnit);
165 // Pass 2: add the preds, succs, etc.
166 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
167 SUnit *SU = &SUnits[su];
168 SDNode *MainNode = SU->Node;
170 if (MainNode->isMachineOpcode()) {
171 unsigned Opc = MainNode->getMachineOpcode();
172 const TargetInstrDesc &TID = TII->get(Opc);
173 for (unsigned i = 0; i != TID.getNumOperands(); ++i) {
174 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
175 SU->isTwoAddress = true;
179 if (TID.isCommutable())
180 SU->isCommutable = true;
183 // Find all predecessors and successors of the group.
184 // Temporarily add N to make code simpler.
185 SU->FlaggedNodes.push_back(MainNode);
187 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
188 SDNode *N = SU->FlaggedNodes[n];
189 if (N->isMachineOpcode() &&
190 TII->get(N->getMachineOpcode()).getImplicitDefs() &&
191 CountResults(N) > TII->get(N->getMachineOpcode()).getNumDefs())
192 SU->hasPhysRegDefs = true;
194 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
195 SDNode *OpN = N->getOperand(i).Val;
196 if (isPassiveNode(OpN)) continue; // Not scheduled.
197 SUnit *OpSU = &SUnits[OpN->getNodeId()];
198 assert(OpSU && "Node has no SUnit!");
199 if (OpSU == SU) continue; // In the same group.
201 MVT OpVT = N->getOperand(i).getValueType();
202 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
203 bool isChain = OpVT == MVT::Other;
205 unsigned PhysReg = 0;
207 // Determine if this is a physical register dependency.
208 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost);
209 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
213 // Remove MainNode from FlaggedNodes again.
214 SU->FlaggedNodes.pop_back();
218 void ScheduleDAG::ComputeLatency(SUnit *SU) {
219 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
221 // Compute the latency for the node. We use the sum of the latencies for
222 // all nodes flagged together into this SUnit.
223 if (InstrItins.isEmpty()) {
224 // No latency information.
230 if (SU->Node->isMachineOpcode()) {
231 unsigned SchedClass = TII->get(SU->Node->getMachineOpcode()).getSchedClass();
232 const InstrStage *S = InstrItins.begin(SchedClass);
233 const InstrStage *E = InstrItins.end(SchedClass);
235 SU->Latency += S->Cycles;
237 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
238 SDNode *FNode = SU->FlaggedNodes[i];
239 if (FNode->isMachineOpcode()) {
240 unsigned SchedClass = TII->get(FNode->getMachineOpcode()).getSchedClass();
241 const InstrStage *S = InstrItins.begin(SchedClass);
242 const InstrStage *E = InstrItins.end(SchedClass);
244 SU->Latency += S->Cycles;
249 /// CalculateDepths - compute depths using algorithms for the longest
251 void ScheduleDAG::CalculateDepths() {
252 unsigned DAGSize = SUnits.size();
253 std::vector<unsigned> InDegree(DAGSize);
254 std::vector<SUnit*> WorkList;
255 WorkList.reserve(DAGSize);
257 // Initialize the data structures
258 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
259 SUnit *SU = &SUnits[i];
260 int NodeNum = SU->NodeNum;
261 unsigned Degree = SU->Preds.size();
262 InDegree[NodeNum] = Degree;
265 // Is it a node without dependencies?
267 assert(SU->Preds.empty() && "SUnit should have no predecessors");
268 // Collect leaf nodes
269 WorkList.push_back(SU);
273 // Process nodes in the topological order
274 while (!WorkList.empty()) {
275 SUnit *SU = WorkList.back();
277 unsigned &SUDepth = SU->Depth;
279 // Use dynamic programming:
280 // When current node is being processed, all of its dependencies
281 // are already processed.
282 // So, just iterate over all predecessors and take the longest path
283 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
285 unsigned PredDepth = I->Dep->Depth;
286 if (PredDepth+1 > SUDepth) {
287 SUDepth = PredDepth + 1;
291 // Update InDegrees of all nodes depending on current SUnit
292 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
295 if (!--InDegree[SU->NodeNum])
296 // If all dependencies of the node are processed already,
297 // then the longest path for the node can be computed now
298 WorkList.push_back(SU);
303 /// CalculateHeights - compute heights using algorithms for the longest
305 void ScheduleDAG::CalculateHeights() {
306 unsigned DAGSize = SUnits.size();
307 std::vector<unsigned> InDegree(DAGSize);
308 std::vector<SUnit*> WorkList;
309 WorkList.reserve(DAGSize);
311 // Initialize the data structures
312 for (unsigned i = 0, e = DAGSize; i != e; ++i) {
313 SUnit *SU = &SUnits[i];
314 int NodeNum = SU->NodeNum;
315 unsigned Degree = SU->Succs.size();
316 InDegree[NodeNum] = Degree;
319 // Is it a node without dependencies?
321 assert(SU->Succs.empty() && "Something wrong");
322 assert(WorkList.empty() && "Should be empty");
323 // Collect leaf nodes
324 WorkList.push_back(SU);
328 // Process nodes in the topological order
329 while (!WorkList.empty()) {
330 SUnit *SU = WorkList.back();
332 unsigned &SUHeight = SU->Height;
334 // Use dynamic programming:
335 // When current node is being processed, all of its dependencies
336 // are already processed.
337 // So, just iterate over all successors and take the longest path
338 for (SUnit::const_succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
340 unsigned SuccHeight = I->Dep->Height;
341 if (SuccHeight+1 > SUHeight) {
342 SUHeight = SuccHeight + 1;
346 // Update InDegrees of all nodes depending on current SUnit
347 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
350 if (!--InDegree[SU->NodeNum])
351 // If all dependencies of the node are processed already,
352 // then the longest path for the node can be computed now
353 WorkList.push_back(SU);
358 /// CountResults - The results of target nodes have register or immediate
359 /// operands first, then an optional chain, and optional flag operands (which do
360 /// not go into the resulting MachineInstr).
361 unsigned ScheduleDAG::CountResults(SDNode *Node) {
362 unsigned N = Node->getNumValues();
363 while (N && Node->getValueType(N - 1) == MVT::Flag)
365 if (N && Node->getValueType(N - 1) == MVT::Other)
366 --N; // Skip over chain result.
370 /// CountOperands - The inputs to target nodes have any actual inputs first,
371 /// followed by special operands that describe memory references, then an
372 /// optional chain operand, then flag operands. Compute the number of
373 /// actual operands that will go into the resulting MachineInstr.
374 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
375 unsigned N = ComputeMemOperandsEnd(Node);
376 while (N && isa<MemOperandSDNode>(Node->getOperand(N - 1).Val))
377 --N; // Ignore MEMOPERAND nodes
381 /// ComputeMemOperandsEnd - Find the index one past the last MemOperandSDNode
383 unsigned ScheduleDAG::ComputeMemOperandsEnd(SDNode *Node) {
384 unsigned N = Node->getNumOperands();
385 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
387 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
388 --N; // Ignore chain if it exists.
392 /// getInstrOperandRegClass - Return register class of the operand of an
393 /// instruction of the specified TargetInstrDesc.
394 static const TargetRegisterClass*
395 getInstrOperandRegClass(const TargetRegisterInfo *TRI,
396 const TargetInstrInfo *TII, const TargetInstrDesc &II,
398 if (Op >= II.getNumOperands()) {
399 assert(II.isVariadic() && "Invalid operand # of instruction");
402 if (II.OpInfo[Op].isLookupPtrRegClass())
403 return TII->getPointerRegClass();
404 return TRI->getRegClass(II.OpInfo[Op].RegClass);
407 /// EmitCopyFromReg - Generate machine code for an CopyFromReg node or an
408 /// implicit physical register output.
409 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
410 bool IsClone, unsigned SrcReg,
411 DenseMap<SDValue, unsigned> &VRBaseMap) {
413 if (TargetRegisterInfo::isVirtualRegister(SrcReg)) {
414 // Just use the input register directly!
415 SDValue Op(Node, ResNo);
418 bool isNew = VRBaseMap.insert(std::make_pair(Op, SrcReg)).second;
419 isNew = isNew; // Silence compiler warning.
420 assert(isNew && "Node emitted out of order - early");
424 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
425 // the CopyToReg'd destination register instead of creating a new vreg.
426 bool MatchReg = true;
427 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
431 if (User->getOpcode() == ISD::CopyToReg &&
432 User->getOperand(2).Val == Node &&
433 User->getOperand(2).ResNo == ResNo) {
434 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
435 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
438 } else if (DestReg != SrcReg)
441 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
442 SDValue Op = User->getOperand(i);
443 if (Op.Val != Node || Op.ResNo != ResNo)
445 MVT VT = Node->getValueType(Op.ResNo);
446 if (VT != MVT::Other && VT != MVT::Flag)
455 const TargetRegisterClass *SrcRC = 0, *DstRC = 0;
456 SrcRC = TRI->getPhysicalRegisterRegClass(SrcReg, Node->getValueType(ResNo));
458 // Figure out the register class to create for the destreg.
460 DstRC = MRI.getRegClass(VRBase);
462 DstRC = TLI->getRegClassFor(Node->getValueType(ResNo));
465 // If all uses are reading from the src physical register and copying the
466 // register is either impossible or very expensive, then don't create a copy.
467 if (MatchReg && SrcRC->getCopyCost() < 0) {
470 // Create the reg, emit the copy.
471 VRBase = MRI.createVirtualRegister(DstRC);
472 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, DstRC, SrcRC);
475 SDValue Op(Node, ResNo);
478 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
479 isNew = isNew; // Silence compiler warning.
480 assert(isNew && "Node emitted out of order - early");
483 /// getDstOfCopyToRegUse - If the only use of the specified result number of
484 /// node is a CopyToReg, return its destination register. Return 0 otherwise.
485 unsigned ScheduleDAG::getDstOfOnlyCopyToRegUse(SDNode *Node,
486 unsigned ResNo) const {
487 if (!Node->hasOneUse())
490 SDNode *User = *Node->use_begin();
491 if (User->getOpcode() == ISD::CopyToReg &&
492 User->getOperand(2).Val == Node &&
493 User->getOperand(2).ResNo == ResNo) {
494 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
495 if (TargetRegisterInfo::isVirtualRegister(Reg))
501 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node, MachineInstr *MI,
502 const TargetInstrDesc &II,
503 DenseMap<SDValue, unsigned> &VRBaseMap) {
504 assert(Node->getMachineOpcode() != TargetInstrInfo::IMPLICIT_DEF &&
505 "IMPLICIT_DEF should have been handled as a special case elsewhere!");
507 for (unsigned i = 0; i < II.getNumDefs(); ++i) {
508 // If the specific node value is only used by a CopyToReg and the dest reg
509 // is a vreg, use the CopyToReg'd destination register instead of creating
512 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
515 if (User->getOpcode() == ISD::CopyToReg &&
516 User->getOperand(2).Val == Node &&
517 User->getOperand(2).ResNo == i) {
518 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
519 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
521 MI->addOperand(MachineOperand::CreateReg(Reg, true));
527 // Create the result registers for this node and add the result regs to
528 // the machine instruction.
530 const TargetRegisterClass *RC = getInstrOperandRegClass(TRI, TII, II, i);
531 assert(RC && "Isn't a register operand!");
532 VRBase = MRI.createVirtualRegister(RC);
533 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
537 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
538 isNew = isNew; // Silence compiler warning.
539 assert(isNew && "Node emitted out of order - early");
543 /// getVR - Return the virtual register corresponding to the specified result
544 /// of the specified node.
545 unsigned ScheduleDAG::getVR(SDValue Op,
546 DenseMap<SDValue, unsigned> &VRBaseMap) {
547 if (Op.isMachineOpcode() &&
548 Op.getMachineOpcode() == TargetInstrInfo::IMPLICIT_DEF) {
549 // Add an IMPLICIT_DEF instruction before every use.
550 unsigned VReg = getDstOfOnlyCopyToRegUse(Op.Val, Op.ResNo);
551 // IMPLICIT_DEF can produce any type of result so its TargetInstrDesc
552 // does not include operand register class info.
554 const TargetRegisterClass *RC = TLI->getRegClassFor(Op.getValueType());
555 VReg = MRI.createVirtualRegister(RC);
557 BuildMI(BB, TII->get(TargetInstrInfo::IMPLICIT_DEF), VReg);
561 DenseMap<SDValue, unsigned>::iterator I = VRBaseMap.find(Op);
562 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
567 /// AddOperand - Add the specified operand to the specified machine instr. II
568 /// specifies the instruction information for the node, and IIOpNum is the
569 /// operand number (in the II) that we are adding. IIOpNum and II are used for
571 void ScheduleDAG::AddOperand(MachineInstr *MI, SDValue Op,
573 const TargetInstrDesc *II,
574 DenseMap<SDValue, unsigned> &VRBaseMap) {
575 if (Op.isMachineOpcode()) {
576 // Note that this case is redundant with the final else block, but we
577 // include it because it is the most common and it makes the logic
579 assert(Op.getValueType() != MVT::Other &&
580 Op.getValueType() != MVT::Flag &&
581 "Chain and flag operands should occur at end of operand list!");
582 // Get/emit the operand.
583 unsigned VReg = getVR(Op, VRBaseMap);
584 const TargetInstrDesc &TID = MI->getDesc();
585 bool isOptDef = IIOpNum < TID.getNumOperands() &&
586 TID.OpInfo[IIOpNum].isOptionalDef();
587 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
589 // Verify that it is right.
590 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
593 // There may be no register class for this operand if it is a variadic
594 // argument (RC will be NULL in this case). In this case, we just assume
595 // the regclass is ok.
596 const TargetRegisterClass *RC =
597 getInstrOperandRegClass(TRI, TII, *II, IIOpNum);
598 assert((RC || II->isVariadic()) && "Expected reg class info!");
599 const TargetRegisterClass *VRC = MRI.getRegClass(VReg);
600 if (RC && VRC != RC) {
601 cerr << "Register class of operand and regclass of use don't agree!\n";
602 cerr << "Operand = " << IIOpNum << "\n";
603 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
604 cerr << "MI = "; MI->print(cerr);
605 cerr << "VReg = " << VReg << "\n";
606 cerr << "VReg RegClass size = " << VRC->getSize()
607 << ", align = " << VRC->getAlignment() << "\n";
608 cerr << "Expected RegClass size = " << RC->getSize()
609 << ", align = " << RC->getAlignment() << "\n";
610 cerr << "Fatal error, aborting.\n";
615 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
616 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
617 } else if (ConstantFPSDNode *F = dyn_cast<ConstantFPSDNode>(Op)) {
618 ConstantFP *CFP = ConstantFP::get(F->getValueAPF());
619 MI->addOperand(MachineOperand::CreateFPImm(CFP));
620 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
621 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
622 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
623 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
624 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
625 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
626 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
627 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
628 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
629 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
630 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
631 int Offset = CP->getOffset();
632 unsigned Align = CP->getAlignment();
633 const Type *Type = CP->getType();
634 // MachineConstantPool wants an explicit alignment.
636 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
638 // Alignment of vector types. FIXME!
639 Align = TM.getTargetData()->getABITypeSize(Type);
640 Align = Log2_64(Align);
645 if (CP->isMachineConstantPoolEntry())
646 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
648 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
649 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
650 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
651 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
653 assert(Op.getValueType() != MVT::Other &&
654 Op.getValueType() != MVT::Flag &&
655 "Chain and flag operands should occur at end of operand list!");
656 unsigned VReg = getVR(Op, VRBaseMap);
657 MI->addOperand(MachineOperand::CreateReg(VReg, false));
659 // Verify that it is right. Note that the reg class of the physreg and the
660 // vreg don't necessarily need to match, but the target copy insertion has
661 // to be able to handle it. This handles things like copies from ST(0) to
662 // an FP vreg on x86.
663 assert(TargetRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
664 if (II && !II->isVariadic()) {
665 assert(getInstrOperandRegClass(TRI, TII, *II, IIOpNum) &&
666 "Don't have operand info for this instruction!");
671 void ScheduleDAG::AddMemOperand(MachineInstr *MI, const MachineMemOperand &MO) {
672 MI->addMemOperand(*MF, MO);
675 /// getSubRegisterRegClass - Returns the register class of specified register
676 /// class' "SubIdx"'th sub-register class.
677 static const TargetRegisterClass*
678 getSubRegisterRegClass(const TargetRegisterClass *TRC, unsigned SubIdx) {
679 // Pick the register class of the subregister
680 TargetRegisterInfo::regclass_iterator I =
681 TRC->subregclasses_begin() + SubIdx-1;
682 assert(I < TRC->subregclasses_end() &&
683 "Invalid subregister index for register class");
687 /// getSuperRegisterRegClass - Returns the register class of a superreg A whose
688 /// "SubIdx"'th sub-register class is the specified register class and whose
689 /// type matches the specified type.
690 static const TargetRegisterClass*
691 getSuperRegisterRegClass(const TargetRegisterClass *TRC,
692 unsigned SubIdx, MVT VT) {
693 // Pick the register class of the superegister for this type
694 for (TargetRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
695 E = TRC->superregclasses_end(); I != E; ++I)
696 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
698 assert(false && "Couldn't find the register class");
702 /// EmitSubregNode - Generate machine code for subreg nodes.
704 void ScheduleDAG::EmitSubregNode(SDNode *Node,
705 DenseMap<SDValue, unsigned> &VRBaseMap) {
707 unsigned Opc = Node->getMachineOpcode();
709 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
710 // the CopyToReg'd destination register instead of creating a new vreg.
711 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
714 if (User->getOpcode() == ISD::CopyToReg &&
715 User->getOperand(2).Val == Node) {
716 unsigned DestReg = cast<RegisterSDNode>(User->getOperand(1))->getReg();
717 if (TargetRegisterInfo::isVirtualRegister(DestReg)) {
724 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
725 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
727 // Create the extract_subreg machine instruction.
728 MachineInstr *MI = BuildMI(*MF, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
730 // Figure out the register class to create for the destreg.
731 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
732 const TargetRegisterClass *TRC = MRI.getRegClass(VReg);
733 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
736 // Grab the destination register
738 const TargetRegisterClass *DRC = MRI.getRegClass(VRBase);
739 assert(SRC && DRC && SRC == DRC &&
740 "Source subregister and destination must have the same class");
744 assert(SRC && "Couldn't find source register class");
745 VRBase = MRI.createVirtualRegister(SRC);
748 // Add def, source, and subreg index
749 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
750 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
751 MI->addOperand(MachineOperand::CreateImm(SubIdx));
753 } else if (Opc == TargetInstrInfo::INSERT_SUBREG ||
754 Opc == TargetInstrInfo::SUBREG_TO_REG) {
755 SDValue N0 = Node->getOperand(0);
756 SDValue N1 = Node->getOperand(1);
757 SDValue N2 = Node->getOperand(2);
758 unsigned SubReg = getVR(N1, VRBaseMap);
759 unsigned SubIdx = cast<ConstantSDNode>(N2)->getValue();
762 // Figure out the register class to create for the destreg.
763 const TargetRegisterClass *TRC = 0;
765 TRC = MRI.getRegClass(VRBase);
767 TRC = getSuperRegisterRegClass(MRI.getRegClass(SubReg), SubIdx,
768 Node->getValueType(0));
769 assert(TRC && "Couldn't determine register class for insert_subreg");
770 VRBase = MRI.createVirtualRegister(TRC); // Create the reg
773 // Create the insert_subreg or subreg_to_reg machine instruction.
774 MachineInstr *MI = BuildMI(*MF, TII->get(Opc));
775 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
777 // If creating a subreg_to_reg, then the first input operand
778 // is an implicit value immediate, otherwise it's a register
779 if (Opc == TargetInstrInfo::SUBREG_TO_REG) {
780 const ConstantSDNode *SD = cast<ConstantSDNode>(N0);
781 MI->addOperand(MachineOperand::CreateImm(SD->getValue()));
783 AddOperand(MI, N0, 0, 0, VRBaseMap);
784 // Add the subregster being inserted
785 AddOperand(MI, N1, 0, 0, VRBaseMap);
786 MI->addOperand(MachineOperand::CreateImm(SubIdx));
789 assert(0 && "Node is not insert_subreg, extract_subreg, or subreg_to_reg");
792 bool isNew = VRBaseMap.insert(std::make_pair(Op, VRBase)).second;
793 isNew = isNew; // Silence compiler warning.
794 assert(isNew && "Node emitted out of order - early");
797 /// EmitNode - Generate machine code for an node and needed dependencies.
799 void ScheduleDAG::EmitNode(SDNode *Node, bool IsClone,
800 DenseMap<SDValue, unsigned> &VRBaseMap) {
801 // If machine instruction
802 if (Node->isMachineOpcode()) {
803 unsigned Opc = Node->getMachineOpcode();
805 // Handle subreg insert/extract specially
806 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
807 Opc == TargetInstrInfo::INSERT_SUBREG ||
808 Opc == TargetInstrInfo::SUBREG_TO_REG) {
809 EmitSubregNode(Node, VRBaseMap);
813 if (Opc == TargetInstrInfo::IMPLICIT_DEF)
814 // We want a unique VR for each IMPLICIT_DEF use.
817 const TargetInstrDesc &II = TII->get(Opc);
818 unsigned NumResults = CountResults(Node);
819 unsigned NodeOperands = CountOperands(Node);
820 unsigned MemOperandsEnd = ComputeMemOperandsEnd(Node);
821 bool HasPhysRegOuts = (NumResults > II.getNumDefs()) &&
822 II.getImplicitDefs() != 0;
824 unsigned NumMIOperands = NodeOperands + NumResults;
825 assert((II.getNumOperands() == NumMIOperands ||
826 HasPhysRegOuts || II.isVariadic()) &&
827 "#operands for dag node doesn't match .td file!");
830 // Create the new machine instruction.
831 MachineInstr *MI = BuildMI(*MF, II);
833 // Add result register values for things that are defined by this
836 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
838 // Emit all of the actual operands of this instruction, adding them to the
839 // instruction as appropriate.
840 for (unsigned i = 0; i != NodeOperands; ++i)
841 AddOperand(MI, Node->getOperand(i), i+II.getNumDefs(), &II, VRBaseMap);
843 // Emit all of the memory operands of this instruction
844 for (unsigned i = NodeOperands; i != MemOperandsEnd; ++i)
845 AddMemOperand(MI, cast<MemOperandSDNode>(Node->getOperand(i))->MO);
847 // Commute node if it has been determined to be profitable.
848 if (CommuteSet.count(Node)) {
849 MachineInstr *NewMI = TII->commuteInstruction(MI);
851 DOUT << "Sched: COMMUTING FAILED!\n";
853 DOUT << "Sched: COMMUTED TO: " << *NewMI;
855 MF->DeleteMachineInstr(MI);
862 if (II.usesCustomDAGSchedInsertionHook())
863 // Insert this instruction into the basic block using a target
864 // specific inserter which may returns a new basic block.
865 BB = TLI->EmitInstrWithCustomInserter(MI, BB);
869 // Additional results must be an physical register def.
870 if (HasPhysRegOuts) {
871 for (unsigned i = II.getNumDefs(); i < NumResults; ++i) {
872 unsigned Reg = II.getImplicitDefs()[i - II.getNumDefs()];
873 if (Node->hasAnyUseOfValue(i))
874 EmitCopyFromReg(Node, i, IsClone, Reg, VRBaseMap);
880 switch (Node->getOpcode()) {
885 assert(0 && "This target-independent node should have been selected!");
887 case ISD::EntryToken:
888 assert(0 && "EntryToken should have been excluded from the schedule!");
890 case ISD::TokenFactor: // fall thru
892 case ISD::CopyToReg: {
894 SDValue SrcVal = Node->getOperand(2);
895 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(SrcVal))
896 SrcReg = R->getReg();
898 SrcReg = getVR(SrcVal, VRBaseMap);
900 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
901 if (SrcReg == DestReg) // Coalesced away the copy? Ignore.
904 const TargetRegisterClass *SrcTRC = 0, *DstTRC = 0;
905 // Get the register classes of the src/dst.
906 if (TargetRegisterInfo::isVirtualRegister(SrcReg))
907 SrcTRC = MRI.getRegClass(SrcReg);
909 SrcTRC = TRI->getPhysicalRegisterRegClass(SrcReg,SrcVal.getValueType());
911 if (TargetRegisterInfo::isVirtualRegister(DestReg))
912 DstTRC = MRI.getRegClass(DestReg);
914 DstTRC = TRI->getPhysicalRegisterRegClass(DestReg,
915 Node->getOperand(1).getValueType());
916 TII->copyRegToReg(*BB, BB->end(), DestReg, SrcReg, DstTRC, SrcTRC);
919 case ISD::CopyFromReg: {
920 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
921 EmitCopyFromReg(Node, 0, IsClone, SrcReg, VRBaseMap);
924 case ISD::INLINEASM: {
925 unsigned NumOps = Node->getNumOperands();
926 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
927 --NumOps; // Ignore the flag operand.
929 // Create the inline asm machine instruction.
930 MachineInstr *MI = BuildMI(*MF, TII->get(TargetInstrInfo::INLINEASM));
932 // Add the asm string as an external symbol operand.
934 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
935 MI->addOperand(MachineOperand::CreateES(AsmStr));
937 // Add all of the operand registers to the instruction.
938 for (unsigned i = 2; i != NumOps;) {
939 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
940 unsigned NumVals = Flags >> 3;
942 MI->addOperand(MachineOperand::CreateImm(Flags));
943 ++i; // Skip the ID value.
946 default: assert(0 && "Bad flags!");
947 case 2: // Def of register.
948 for (; NumVals; --NumVals, ++i) {
949 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
950 MI->addOperand(MachineOperand::CreateReg(Reg, true));
953 case 1: // Use of register.
954 case 3: // Immediate.
955 case 4: // Addressing mode.
956 // The addressing mode has been selected, just add all of the
957 // operands to the machine instruction.
958 for (; NumVals; --NumVals, ++i)
959 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
969 void ScheduleDAG::EmitNoop() {
970 TII->insertNoop(*BB, BB->end());
973 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU,
974 DenseMap<SUnit*, unsigned> &VRBaseMap) {
975 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
977 if (I->isCtrl) continue; // ignore chain preds
979 // Copy to physical register.
980 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
981 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
982 // Find the destination physical register.
984 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
985 EE = SU->Succs.end(); II != EE; ++II) {
991 assert(I->Reg && "Unknown physical register!");
992 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
993 SU->CopyDstRC, SU->CopySrcRC);
995 // Copy from physical register.
996 assert(I->Reg && "Unknown physical register!");
997 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC);
998 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second;
999 isNew = isNew; // Silence compiler warning.
1000 assert(isNew && "Node emitted out of order - early");
1001 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
1002 SU->CopyDstRC, SU->CopySrcRC);
1008 /// EmitLiveInCopy - Emit a copy for a live in physical register. If the
1009 /// physical register has only a single copy use, then coalesced the copy
1011 void ScheduleDAG::EmitLiveInCopy(MachineBasicBlock *MBB,
1012 MachineBasicBlock::iterator &InsertPos,
1013 unsigned VirtReg, unsigned PhysReg,
1014 const TargetRegisterClass *RC,
1015 DenseMap<MachineInstr*, unsigned> &CopyRegMap){
1016 unsigned NumUses = 0;
1017 MachineInstr *UseMI = NULL;
1018 for (MachineRegisterInfo::use_iterator UI = MRI.use_begin(VirtReg),
1019 UE = MRI.use_end(); UI != UE; ++UI) {
1025 // If the number of uses is not one, or the use is not a move instruction,
1026 // don't coalesce. Also, only coalesce away a virtual register to virtual
1028 bool Coalesced = false;
1029 unsigned SrcReg, DstReg;
1031 TII->isMoveInstr(*UseMI, SrcReg, DstReg) &&
1032 TargetRegisterInfo::isVirtualRegister(DstReg)) {
1037 // Now find an ideal location to insert the copy.
1038 MachineBasicBlock::iterator Pos = InsertPos;
1039 while (Pos != MBB->begin()) {
1040 MachineInstr *PrevMI = prior(Pos);
1041 DenseMap<MachineInstr*, unsigned>::iterator RI = CopyRegMap.find(PrevMI);
1042 // copyRegToReg might emit multiple instructions to do a copy.
1043 unsigned CopyDstReg = (RI == CopyRegMap.end()) ? 0 : RI->second;
1044 if (CopyDstReg && !TRI->regsOverlap(CopyDstReg, PhysReg))
1045 // This is what the BB looks like right now:
1050 // We want to insert "r1025 = mov r1". Inserting this copy below the
1051 // move to r1024 makes it impossible for that move to be coalesced.
1058 break; // Woot! Found a good location.
1062 TII->copyRegToReg(*MBB, Pos, VirtReg, PhysReg, RC, RC);
1063 CopyRegMap.insert(std::make_pair(prior(Pos), VirtReg));
1065 if (&*InsertPos == UseMI) ++InsertPos;
1070 /// EmitLiveInCopies - If this is the first basic block in the function,
1071 /// and if it has live ins that need to be copied into vregs, emit the
1072 /// copies into the top of the block.
1073 void ScheduleDAG::EmitLiveInCopies(MachineBasicBlock *MBB) {
1074 DenseMap<MachineInstr*, unsigned> CopyRegMap;
1075 MachineBasicBlock::iterator InsertPos = MBB->begin();
1076 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1077 E = MRI.livein_end(); LI != E; ++LI)
1079 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1080 EmitLiveInCopy(MBB, InsertPos, LI->second, LI->first, RC, CopyRegMap);
1084 /// EmitSchedule - Emit the machine code in scheduled order.
1085 MachineBasicBlock *ScheduleDAG::EmitSchedule() {
1086 bool isEntryBB = &MF->front() == BB;
1088 if (isEntryBB && !SchedLiveInCopies) {
1089 // If this is the first basic block in the function, and if it has live ins
1090 // that need to be copied into vregs, emit the copies into the top of the
1091 // block before emitting the code for the block.
1092 for (MachineRegisterInfo::livein_iterator LI = MRI.livein_begin(),
1093 E = MRI.livein_end(); LI != E; ++LI)
1095 const TargetRegisterClass *RC = MRI.getRegClass(LI->second);
1096 TII->copyRegToReg(*MF->begin(), MF->begin()->end(), LI->second,
1101 // Finally, emit the code for all of the scheduled instructions.
1102 DenseMap<SDValue, unsigned> VRBaseMap;
1103 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
1104 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1105 SUnit *SU = Sequence[i];
1107 // Null SUnit* is a noop.
1111 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
1112 EmitNode(SU->FlaggedNodes[j], SU->OrigNode != SU, VRBaseMap);
1114 EmitCrossRCCopy(SU, CopyVRBaseMap);
1116 EmitNode(SU->Node, SU->OrigNode != SU, VRBaseMap);
1119 if (isEntryBB && SchedLiveInCopies)
1120 EmitLiveInCopies(MF->begin());
1125 /// dump - dump the schedule.
1126 void ScheduleDAG::dumpSchedule() const {
1127 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
1128 if (SUnit *SU = Sequence[i])
1131 cerr << "**** NOOP ****\n";
1136 /// Run - perform scheduling.
1138 void ScheduleDAG::Run() {
1141 DOUT << "*** Final schedule ***\n";
1142 DEBUG(dumpSchedule());
1146 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
1147 /// a group of nodes flagged together.
1148 void SUnit::dump(const SelectionDAG *G) const {
1149 cerr << "SU(" << NodeNum << "): ";
1153 cerr << "CROSS RC COPY ";
1155 if (FlaggedNodes.size() != 0) {
1156 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
1158 FlaggedNodes[i]->dump(G);
1164 void SUnit::dumpAll(const SelectionDAG *G) const {
1167 cerr << " # preds left : " << NumPredsLeft << "\n";
1168 cerr << " # succs left : " << NumSuccsLeft << "\n";
1169 cerr << " Latency : " << Latency << "\n";
1170 cerr << " Depth : " << Depth << "\n";
1171 cerr << " Height : " << Height << "\n";
1173 if (Preds.size() != 0) {
1174 cerr << " Predecessors:\n";
1175 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
1181 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
1187 if (Succs.size() != 0) {
1188 cerr << " Successors:\n";
1189 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
1195 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";