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/Type.h"
18 #include "llvm/CodeGen/ScheduleDAG.h"
19 #include "llvm/CodeGen/MachineConstantPool.h"
20 #include "llvm/CodeGen/MachineFunction.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/Support/Debug.h"
27 #include "llvm/Support/MathExtras.h"
30 ScheduleDAG::ScheduleDAG(SelectionDAG &dag, MachineBasicBlock *bb,
31 const TargetMachine &tm)
32 : DAG(dag), BB(bb), TM(tm), RegInfo(BB->getParent()->getRegInfo()) {
33 TII = TM.getInstrInfo();
34 MRI = TM.getRegisterInfo();
35 ConstPool = BB->getParent()->getConstantPool();
38 /// CheckForPhysRegDependency - Check if the dependency between def and use of
39 /// a specified operand is a physical register dependency. If so, returns the
40 /// register and the cost of copying the register.
41 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
42 const MRegisterInfo *MRI,
43 const TargetInstrInfo *TII,
44 unsigned &PhysReg, int &Cost) {
45 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
48 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
49 if (MRegisterInfo::isVirtualRegister(Reg))
52 unsigned ResNo = Use->getOperand(2).ResNo;
53 if (Def->isTargetOpcode()) {
54 const TargetInstrDescriptor &II = TII->get(Def->getTargetOpcode());
55 if (ResNo >= II.numDefs &&
56 II.ImplicitDefs[ResNo - II.numDefs] == Reg) {
58 const TargetRegisterClass *RC =
59 MRI->getPhysicalRegisterRegClass(Def->getValueType(ResNo), Reg);
60 Cost = RC->getCopyCost();
65 SUnit *ScheduleDAG::Clone(SUnit *Old) {
66 SUnit *SU = NewSUnit(Old->Node);
67 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
68 SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
69 SU->InstanceNo = SUnitMap[Old->Node].size();
70 SU->Latency = Old->Latency;
71 SU->isTwoAddress = Old->isTwoAddress;
72 SU->isCommutable = Old->isCommutable;
73 SU->hasPhysRegDefs = Old->hasPhysRegDefs;
74 SUnitMap[Old->Node].push_back(SU);
79 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
80 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
81 /// together nodes with a single SUnit.
82 void ScheduleDAG::BuildSchedUnits() {
83 // Reserve entries in the vector for each of the SUnits we are creating. This
84 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
86 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
88 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
89 E = DAG.allnodes_end(); NI != E; ++NI) {
90 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
93 // If this node has already been processed, stop now.
94 if (SUnitMap[NI].size()) continue;
96 SUnit *NodeSUnit = NewSUnit(NI);
98 // See if anything is flagged to this node, if so, add them to flagged
99 // nodes. Nodes can have at most one flag input and one flag output. Flags
100 // are required the be the last operand and result of a node.
102 // Scan up, adding flagged preds to FlaggedNodes.
104 if (N->getNumOperands() &&
105 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
107 N = N->getOperand(N->getNumOperands()-1).Val;
108 NodeSUnit->FlaggedNodes.push_back(N);
109 SUnitMap[N].push_back(NodeSUnit);
110 } while (N->getNumOperands() &&
111 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
112 std::reverse(NodeSUnit->FlaggedNodes.begin(),
113 NodeSUnit->FlaggedNodes.end());
116 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
117 // have a user of the flag operand.
119 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
120 SDOperand FlagVal(N, N->getNumValues()-1);
122 // There are either zero or one users of the Flag result.
123 bool HasFlagUse = false;
124 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
126 if (FlagVal.isOperand(*UI)) {
128 NodeSUnit->FlaggedNodes.push_back(N);
129 SUnitMap[N].push_back(NodeSUnit);
133 if (!HasFlagUse) break;
136 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
139 SUnitMap[N].push_back(NodeSUnit);
141 ComputeLatency(NodeSUnit);
144 // Pass 2: add the preds, succs, etc.
145 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
146 SUnit *SU = &SUnits[su];
147 SDNode *MainNode = SU->Node;
149 if (MainNode->isTargetOpcode()) {
150 unsigned Opc = MainNode->getTargetOpcode();
151 const TargetInstrDescriptor &TID = TII->get(Opc);
152 for (unsigned i = 0; i != TID.numOperands; ++i) {
153 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
154 SU->isTwoAddress = true;
158 if (TID.Flags & M_COMMUTABLE)
159 SU->isCommutable = true;
162 // Find all predecessors and successors of the group.
163 // Temporarily add N to make code simpler.
164 SU->FlaggedNodes.push_back(MainNode);
166 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
167 SDNode *N = SU->FlaggedNodes[n];
168 if (N->isTargetOpcode() &&
169 TII->getImplicitDefs(N->getTargetOpcode()) &&
170 CountResults(N) > (unsigned)TII->getNumDefs(N->getTargetOpcode()))
171 SU->hasPhysRegDefs = true;
173 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
174 SDNode *OpN = N->getOperand(i).Val;
175 if (isPassiveNode(OpN)) continue; // Not scheduled.
176 SUnit *OpSU = SUnitMap[OpN].front();
177 assert(OpSU && "Node has no SUnit!");
178 if (OpSU == SU) continue; // In the same group.
180 MVT::ValueType OpVT = N->getOperand(i).getValueType();
181 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
182 bool isChain = OpVT == MVT::Other;
184 unsigned PhysReg = 0;
186 // Determine if this is a physical register dependency.
187 CheckForPhysRegDependency(OpN, N, i, MRI, TII, PhysReg, Cost);
188 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
192 // Remove MainNode from FlaggedNodes again.
193 SU->FlaggedNodes.pop_back();
199 void ScheduleDAG::ComputeLatency(SUnit *SU) {
200 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
202 // Compute the latency for the node. We use the sum of the latencies for
203 // all nodes flagged together into this SUnit.
204 if (InstrItins.isEmpty()) {
205 // No latency information.
209 if (SU->Node->isTargetOpcode()) {
210 unsigned SchedClass =
211 TII->get(SU->Node->getTargetOpcode()).getSchedClass();
212 InstrStage *S = InstrItins.begin(SchedClass);
213 InstrStage *E = InstrItins.end(SchedClass);
215 SU->Latency += S->Cycles;
217 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
218 SDNode *FNode = SU->FlaggedNodes[i];
219 if (FNode->isTargetOpcode()) {
220 unsigned SchedClass =TII->get(FNode->getTargetOpcode()).getSchedClass();
221 InstrStage *S = InstrItins.begin(SchedClass);
222 InstrStage *E = InstrItins.end(SchedClass);
224 SU->Latency += S->Cycles;
230 void ScheduleDAG::CalculateDepths() {
231 std::vector<std::pair<SUnit*, unsigned> > WorkList;
232 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
233 if (SUnits[i].Preds.size() == 0)
234 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
236 while (!WorkList.empty()) {
237 SUnit *SU = WorkList.back().first;
238 unsigned Depth = WorkList.back().second;
240 if (SU->Depth == 0 || Depth > SU->Depth) {
242 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
244 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
249 void ScheduleDAG::CalculateHeights() {
250 std::vector<std::pair<SUnit*, unsigned> > WorkList;
251 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
252 WorkList.push_back(std::make_pair(Root, 0U));
254 while (!WorkList.empty()) {
255 SUnit *SU = WorkList.back().first;
256 unsigned Height = WorkList.back().second;
258 if (SU->Height == 0 || Height > SU->Height) {
260 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
262 WorkList.push_back(std::make_pair(I->Dep, Height+1));
267 /// CountResults - The results of target nodes have register or immediate
268 /// operands first, then an optional chain, and optional flag operands (which do
269 /// not go into the machine instrs.)
270 unsigned ScheduleDAG::CountResults(SDNode *Node) {
271 unsigned N = Node->getNumValues();
272 while (N && Node->getValueType(N - 1) == MVT::Flag)
274 if (N && Node->getValueType(N - 1) == MVT::Other)
275 --N; // Skip over chain result.
279 /// CountOperands The inputs to target nodes have any actual inputs first,
280 /// followed by an optional chain operand, then flag operands. Compute the
281 /// number of actual operands that will go into the machine instr.
282 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
283 unsigned N = Node->getNumOperands();
284 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
286 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
287 --N; // Ignore chain if it exists.
291 static const TargetRegisterClass *getInstrOperandRegClass(
292 const MRegisterInfo *MRI,
293 const TargetInstrInfo *TII,
294 const TargetInstrDescriptor *II,
296 if (Op >= II->numOperands) {
297 assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
300 if (II->OpInfo[Op].isLookupPtrRegClass())
301 return TII->getPointerRegClass();
302 return MRI->getRegClass(II->OpInfo[Op].RegClass);
305 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
306 unsigned InstanceNo, unsigned SrcReg,
307 DenseMap<SDOperand, unsigned> &VRBaseMap) {
309 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
310 // Just use the input register directly!
312 VRBaseMap.erase(SDOperand(Node, ResNo));
313 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
314 assert(isNew && "Node emitted out of order - early");
318 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
319 // the CopyToReg'd destination register instead of creating a new vreg.
320 bool MatchReg = true;
321 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
325 if (Use->getOpcode() == ISD::CopyToReg &&
326 Use->getOperand(2).Val == Node &&
327 Use->getOperand(2).ResNo == ResNo) {
328 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
329 if (MRegisterInfo::isVirtualRegister(DestReg)) {
332 } else if (DestReg != SrcReg)
335 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
336 SDOperand Op = Use->getOperand(i);
337 if (Op.Val != Node || Op.ResNo != ResNo)
339 MVT::ValueType VT = Node->getValueType(Op.ResNo);
340 if (VT != MVT::Other && VT != MVT::Flag)
349 const TargetRegisterClass *TRC = 0;
350 // Figure out the register class to create for the destreg.
352 TRC = RegInfo.getRegClass(VRBase);
354 TRC = MRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
356 // If all uses are reading from the src physical register and copying the
357 // register is either impossible or very expensive, then don't create a copy.
358 if (MatchReg && TRC->getCopyCost() < 0) {
361 // Create the reg, emit the copy.
362 VRBase = RegInfo.createVirtualRegister(TRC);
363 TII->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
367 VRBaseMap.erase(SDOperand(Node, ResNo));
368 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
369 assert(isNew && "Node emitted out of order - early");
372 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
374 const TargetInstrDescriptor &II,
375 DenseMap<SDOperand, unsigned> &VRBaseMap) {
376 for (unsigned i = 0; i < II.numDefs; ++i) {
377 // If the specific node value is only used by a CopyToReg and the dest reg
378 // is a vreg, use the CopyToReg'd destination register instead of creating
381 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
384 if (Use->getOpcode() == ISD::CopyToReg &&
385 Use->getOperand(2).Val == Node &&
386 Use->getOperand(2).ResNo == i) {
387 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
388 if (MRegisterInfo::isVirtualRegister(Reg)) {
390 MI->addOperand(MachineOperand::CreateReg(Reg, true));
396 // Create the result registers for this node and add the result regs to
397 // the machine instruction.
399 const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
400 assert(RC && "Isn't a register operand!");
401 VRBase = RegInfo.createVirtualRegister(RC);
402 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
405 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
406 assert(isNew && "Node emitted out of order - early");
410 /// getVR - Return the virtual register corresponding to the specified result
411 /// of the specified node.
412 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
413 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
414 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
419 /// AddOperand - Add the specified operand to the specified machine instr. II
420 /// specifies the instruction information for the node, and IIOpNum is the
421 /// operand number (in the II) that we are adding. IIOpNum and II are used for
423 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
425 const TargetInstrDescriptor *II,
426 DenseMap<SDOperand, unsigned> &VRBaseMap) {
427 if (Op.isTargetOpcode()) {
428 // Note that this case is redundant with the final else block, but we
429 // include it because it is the most common and it makes the logic
431 assert(Op.getValueType() != MVT::Other &&
432 Op.getValueType() != MVT::Flag &&
433 "Chain and flag operands should occur at end of operand list!");
435 // Get/emit the operand.
436 unsigned VReg = getVR(Op, VRBaseMap);
437 const TargetInstrDescriptor *TID = MI->getDesc();
438 bool isOptDef = (IIOpNum < TID->numOperands)
439 ? (TID->OpInfo[IIOpNum].isOptionalDef()) : false;
440 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
442 // Verify that it is right.
443 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
445 const TargetRegisterClass *RC =
446 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
447 assert(RC && "Don't have operand info for this instruction!");
448 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
450 cerr << "Register class of operand and regclass of use don't agree!\n";
452 cerr << "Operand = " << IIOpNum << "\n";
453 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
454 cerr << "MI = "; MI->print(cerr);
455 cerr << "VReg = " << VReg << "\n";
456 cerr << "VReg RegClass size = " << VRC->getSize()
457 << ", align = " << VRC->getAlignment() << "\n";
458 cerr << "Expected RegClass size = " << RC->getSize()
459 << ", align = " << RC->getAlignment() << "\n";
461 cerr << "Fatal error, aborting.\n";
465 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
466 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
467 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
468 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
469 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
470 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
471 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
472 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
473 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
474 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
475 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
476 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
477 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
478 int Offset = CP->getOffset();
479 unsigned Align = CP->getAlignment();
480 const Type *Type = CP->getType();
481 // MachineConstantPool wants an explicit alignment.
483 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
485 // Alignment of vector types. FIXME!
486 Align = TM.getTargetData()->getABITypeSize(Type);
487 Align = Log2_64(Align);
492 if (CP->isMachineConstantPoolEntry())
493 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
495 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
496 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
497 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
498 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
500 assert(Op.getValueType() != MVT::Other &&
501 Op.getValueType() != MVT::Flag &&
502 "Chain and flag operands should occur at end of operand list!");
503 unsigned VReg = getVR(Op, VRBaseMap);
504 MI->addOperand(MachineOperand::CreateReg(VReg, false));
506 // Verify that it is right.
507 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
509 const TargetRegisterClass *RC =
510 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
511 assert(RC && "Don't have operand info for this instruction!");
512 assert(RegInfo.getRegClass(VReg) == RC &&
513 "Register class of operand and regclass of use don't agree!");
519 // Returns the Register Class of a subregister
520 static const TargetRegisterClass *getSubRegisterRegClass(
521 const TargetRegisterClass *TRC,
523 // Pick the register class of the subregister
524 MRegisterInfo::regclass_iterator I = TRC->subregclasses_begin() + SubIdx-1;
525 assert(I < TRC->subregclasses_end() &&
526 "Invalid subregister index for register class");
530 static const TargetRegisterClass *getSuperregRegisterClass(
531 const TargetRegisterClass *TRC,
534 // Pick the register class of the superegister for this type
535 for (MRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
536 E = TRC->superregclasses_end(); I != E; ++I)
537 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
539 assert(false && "Couldn't find the register class");
543 /// EmitSubregNode - Generate machine code for subreg nodes.
545 void ScheduleDAG::EmitSubregNode(SDNode *Node,
546 DenseMap<SDOperand, unsigned> &VRBaseMap) {
548 unsigned Opc = Node->getTargetOpcode();
549 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
550 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
551 // the CopyToReg'd destination register instead of creating a new vreg.
552 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
555 if (Use->getOpcode() == ISD::CopyToReg &&
556 Use->getOperand(2).Val == Node) {
557 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
558 if (MRegisterInfo::isVirtualRegister(DestReg)) {
565 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
567 // TODO: If the node is a use of a CopyFromReg from a physical register
568 // fold the extract into the copy now
570 // Create the extract_subreg machine instruction.
572 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
574 // Figure out the register class to create for the destreg.
575 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
576 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
577 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
580 // Grab the destination register
581 const TargetRegisterClass *DRC = 0;
582 DRC = RegInfo.getRegClass(VRBase);
584 "Source subregister and destination must have the same class");
587 VRBase = RegInfo.createVirtualRegister(SRC);
590 // Add def, source, and subreg index
591 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
592 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
593 MI->addOperand(MachineOperand::CreateImm(SubIdx));
595 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
596 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
597 "Malformed insert_subreg node");
598 bool isUndefInput = (Node->getNumOperands() == 2);
603 SubReg = getVR(Node->getOperand(0), VRBaseMap);
604 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
606 SubReg = getVR(Node->getOperand(1), VRBaseMap);
607 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
610 // TODO: Add tracking info to MachineRegisterInfo of which vregs are subregs
611 // to allow coalescing in the allocator
613 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
614 // the CopyToReg'd destination register instead of creating a new vreg.
615 // If the CopyToReg'd destination register is physical, then fold the
616 // insert into the copy
617 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
620 if (Use->getOpcode() == ISD::CopyToReg &&
621 Use->getOperand(2).Val == Node) {
622 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
623 if (MRegisterInfo::isVirtualRegister(DestReg)) {
630 // Create the insert_subreg machine instruction.
632 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
634 // Figure out the register class to create for the destreg.
635 const TargetRegisterClass *TRC = 0;
637 TRC = RegInfo.getRegClass(VRBase);
639 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
640 Node->getValueType(0));
641 assert(TRC && "Couldn't determine register class for insert_subreg");
642 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
645 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
646 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
648 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
649 MI->addOperand(MachineOperand::CreateImm(SubIdx));
651 assert(0 && "Node is not a subreg insert or extract");
653 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
654 assert(isNew && "Node emitted out of order - early");
657 /// EmitNode - Generate machine code for an node and needed dependencies.
659 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
660 DenseMap<SDOperand, unsigned> &VRBaseMap) {
661 // If machine instruction
662 if (Node->isTargetOpcode()) {
663 unsigned Opc = Node->getTargetOpcode();
665 // Handle subreg insert/extract specially
666 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
667 Opc == TargetInstrInfo::INSERT_SUBREG) {
668 EmitSubregNode(Node, VRBaseMap);
672 const TargetInstrDescriptor &II = TII->get(Opc);
674 unsigned NumResults = CountResults(Node);
675 unsigned NodeOperands = CountOperands(Node);
676 unsigned NumMIOperands = NodeOperands + NumResults;
677 bool HasPhysRegOuts = (NumResults > II.numDefs) && II.ImplicitDefs;
679 assert((unsigned(II.numOperands) == NumMIOperands ||
680 HasPhysRegOuts || (II.Flags & M_VARIABLE_OPS)) &&
681 "#operands for dag node doesn't match .td file!");
684 // Create the new machine instruction.
685 MachineInstr *MI = new MachineInstr(II);
687 // Add result register values for things that are defined by this
690 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
692 // Emit all of the actual operands of this instruction, adding them to the
693 // instruction as appropriate.
694 for (unsigned i = 0; i != NodeOperands; ++i)
695 AddOperand(MI, Node->getOperand(i), i+II.numDefs, &II, VRBaseMap);
697 // Commute node if it has been determined to be profitable.
698 if (CommuteSet.count(Node)) {
699 MachineInstr *NewMI = TII->commuteInstruction(MI);
701 DOUT << "Sched: COMMUTING FAILED!\n";
703 DOUT << "Sched: COMMUTED TO: " << *NewMI;
711 // Now that we have emitted all operands, emit this instruction itself.
712 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
713 BB->insert(BB->end(), MI);
715 // Insert this instruction into the end of the basic block, potentially
716 // taking some custom action.
717 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
720 // Additional results must be an physical register def.
721 if (HasPhysRegOuts) {
722 for (unsigned i = II.numDefs; i < NumResults; ++i) {
723 unsigned Reg = II.ImplicitDefs[i - II.numDefs];
724 if (Node->hasAnyUseOfValue(i))
725 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
729 switch (Node->getOpcode()) {
734 assert(0 && "This target-independent node should have been selected!");
735 case ISD::EntryToken: // fall thru
736 case ISD::TokenFactor:
739 case ISD::CopyToReg: {
741 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
744 InReg = getVR(Node->getOperand(2), VRBaseMap);
745 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
746 if (InReg != DestReg) {// Coalesced away the copy?
747 const TargetRegisterClass *TRC = 0;
748 // Get the target register class
749 if (MRegisterInfo::isVirtualRegister(InReg))
750 TRC = RegInfo.getRegClass(InReg);
753 MRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
755 TII->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
759 case ISD::CopyFromReg: {
760 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
761 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
764 case ISD::INLINEASM: {
765 unsigned NumOps = Node->getNumOperands();
766 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
767 --NumOps; // Ignore the flag operand.
769 // Create the inline asm machine instruction.
771 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
773 // Add the asm string as an external symbol operand.
775 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
776 MI->addOperand(MachineOperand::CreateES(AsmStr));
778 // Add all of the operand registers to the instruction.
779 for (unsigned i = 2; i != NumOps;) {
780 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
781 unsigned NumVals = Flags >> 3;
783 MI->addOperand(MachineOperand::CreateImm(Flags));
784 ++i; // Skip the ID value.
787 default: assert(0 && "Bad flags!");
788 case 1: // Use of register.
789 for (; NumVals; --NumVals, ++i) {
790 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
791 MI->addOperand(MachineOperand::CreateReg(Reg, false));
794 case 2: // Def of register.
795 for (; NumVals; --NumVals, ++i) {
796 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
797 MI->addOperand(MachineOperand::CreateReg(Reg, true));
800 case 3: { // Immediate.
801 for (; NumVals; --NumVals, ++i) {
802 if (ConstantSDNode *CS =
803 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
804 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
805 } else if (GlobalAddressSDNode *GA =
806 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
807 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
810 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
811 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
816 case 4: // Addressing mode.
817 // The addressing mode has been selected, just add all of the
818 // operands to the machine instruction.
819 for (; NumVals; --NumVals, ++i)
820 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
830 void ScheduleDAG::EmitNoop() {
831 TII->insertNoop(*BB, BB->end());
834 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
835 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
837 if (I->isCtrl) continue; // ignore chain preds
839 // Copy to physical register.
840 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
841 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
842 // Find the destination physical register.
844 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
845 EE = SU->Succs.end(); II != EE; ++II) {
851 assert(I->Reg && "Unknown physical register!");
852 TII->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
853 SU->CopyDstRC, SU->CopySrcRC);
855 // Copy from physical register.
856 assert(I->Reg && "Unknown physical register!");
857 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
858 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
859 assert(isNew && "Node emitted out of order - early");
860 TII->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
861 SU->CopyDstRC, SU->CopySrcRC);
867 /// EmitSchedule - Emit the machine code in scheduled order.
868 void ScheduleDAG::EmitSchedule() {
869 // If this is the first basic block in the function, and if it has live ins
870 // that need to be copied into vregs, emit the copies into the top of the
871 // block before emitting the code for the block.
872 MachineFunction &MF = DAG.getMachineFunction();
873 if (&MF.front() == BB) {
874 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
875 E = RegInfo.livein_end(); LI != E; ++LI)
877 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
878 TII->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
884 // Finally, emit the code for all of the scheduled instructions.
885 DenseMap<SDOperand, unsigned> VRBaseMap;
886 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
887 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
888 if (SUnit *SU = Sequence[i]) {
889 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
890 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
892 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
894 EmitCrossRCCopy(SU, CopyVRBaseMap);
896 // Null SUnit* is a noop.
902 /// dump - dump the schedule.
903 void ScheduleDAG::dumpSchedule() const {
904 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
905 if (SUnit *SU = Sequence[i])
908 cerr << "**** NOOP ****\n";
913 /// Run - perform scheduling.
915 MachineBasicBlock *ScheduleDAG::Run() {
920 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
921 /// a group of nodes flagged together.
922 void SUnit::dump(const SelectionDAG *G) const {
923 cerr << "SU(" << NodeNum << "): ";
927 cerr << "CROSS RC COPY ";
929 if (FlaggedNodes.size() != 0) {
930 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
932 FlaggedNodes[i]->dump(G);
938 void SUnit::dumpAll(const SelectionDAG *G) const {
941 cerr << " # preds left : " << NumPredsLeft << "\n";
942 cerr << " # succs left : " << NumSuccsLeft << "\n";
943 cerr << " Latency : " << Latency << "\n";
944 cerr << " Depth : " << Depth << "\n";
945 cerr << " Height : " << Height << "\n";
947 if (Preds.size() != 0) {
948 cerr << " Predecessors:\n";
949 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
955 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
961 if (Succs.size() != 0) {
962 cerr << " Successors:\n";
963 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
969 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";