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 = TII->getSchedClass(SU->Node->getTargetOpcode());
211 InstrStage *S = InstrItins.begin(SchedClass);
212 InstrStage *E = InstrItins.end(SchedClass);
214 SU->Latency += S->Cycles;
216 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i) {
217 SDNode *FNode = SU->FlaggedNodes[i];
218 if (FNode->isTargetOpcode()) {
219 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
220 InstrStage *S = InstrItins.begin(SchedClass);
221 InstrStage *E = InstrItins.end(SchedClass);
223 SU->Latency += S->Cycles;
229 void ScheduleDAG::CalculateDepths() {
230 std::vector<std::pair<SUnit*, unsigned> > WorkList;
231 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
232 if (SUnits[i].Preds.size() == 0)
233 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
235 while (!WorkList.empty()) {
236 SUnit *SU = WorkList.back().first;
237 unsigned Depth = WorkList.back().second;
239 if (SU->Depth == 0 || Depth > SU->Depth) {
241 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
243 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
248 void ScheduleDAG::CalculateHeights() {
249 std::vector<std::pair<SUnit*, unsigned> > WorkList;
250 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
251 WorkList.push_back(std::make_pair(Root, 0U));
253 while (!WorkList.empty()) {
254 SUnit *SU = WorkList.back().first;
255 unsigned Height = WorkList.back().second;
257 if (SU->Height == 0 || Height > SU->Height) {
259 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
261 WorkList.push_back(std::make_pair(I->Dep, Height+1));
266 /// CountResults - The results of target nodes have register or immediate
267 /// operands first, then an optional chain, and optional flag operands (which do
268 /// not go into the machine instrs.)
269 unsigned ScheduleDAG::CountResults(SDNode *Node) {
270 unsigned N = Node->getNumValues();
271 while (N && Node->getValueType(N - 1) == MVT::Flag)
273 if (N && Node->getValueType(N - 1) == MVT::Other)
274 --N; // Skip over chain result.
278 /// CountOperands The inputs to target nodes have any actual inputs first,
279 /// followed by an optional chain operand, then flag operands. Compute the
280 /// number of actual operands that will go into the machine instr.
281 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
282 unsigned N = Node->getNumOperands();
283 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
285 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
286 --N; // Ignore chain if it exists.
290 static const TargetRegisterClass *getInstrOperandRegClass(
291 const MRegisterInfo *MRI,
292 const TargetInstrInfo *TII,
293 const TargetInstrDescriptor *II,
295 if (Op >= II->numOperands) {
296 assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
299 const TargetOperandInfo &toi = II->OpInfo[Op];
300 return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
301 ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
304 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
305 unsigned InstanceNo, unsigned SrcReg,
306 DenseMap<SDOperand, unsigned> &VRBaseMap) {
308 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
309 // Just use the input register directly!
311 VRBaseMap.erase(SDOperand(Node, ResNo));
312 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
313 assert(isNew && "Node emitted out of order - early");
317 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
318 // the CopyToReg'd destination register instead of creating a new vreg.
319 bool MatchReg = true;
320 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
324 if (Use->getOpcode() == ISD::CopyToReg &&
325 Use->getOperand(2).Val == Node &&
326 Use->getOperand(2).ResNo == ResNo) {
327 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
328 if (MRegisterInfo::isVirtualRegister(DestReg)) {
331 } else if (DestReg != SrcReg)
334 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
335 SDOperand Op = Use->getOperand(i);
336 if (Op.Val != Node || Op.ResNo != ResNo)
338 MVT::ValueType VT = Node->getValueType(Op.ResNo);
339 if (VT != MVT::Other && VT != MVT::Flag)
348 const TargetRegisterClass *TRC = 0;
349 // Figure out the register class to create for the destreg.
351 TRC = RegInfo.getRegClass(VRBase);
353 TRC = MRI->getPhysicalRegisterRegClass(Node->getValueType(ResNo), SrcReg);
355 // If all uses are reading from the src physical register and copying the
356 // register is either impossible or very expensive, then don't create a copy.
357 if (MatchReg && TRC->getCopyCost() < 0) {
360 // Create the reg, emit the copy.
361 VRBase = RegInfo.createVirtualRegister(TRC);
362 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC, TRC);
366 VRBaseMap.erase(SDOperand(Node, ResNo));
367 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
368 assert(isNew && "Node emitted out of order - early");
371 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
373 const TargetInstrDescriptor &II,
374 DenseMap<SDOperand, unsigned> &VRBaseMap) {
375 for (unsigned i = 0; i < II.numDefs; ++i) {
376 // If the specific node value is only used by a CopyToReg and the dest reg
377 // is a vreg, use the CopyToReg'd destination register instead of creating
380 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
383 if (Use->getOpcode() == ISD::CopyToReg &&
384 Use->getOperand(2).Val == Node &&
385 Use->getOperand(2).ResNo == i) {
386 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
387 if (MRegisterInfo::isVirtualRegister(Reg)) {
389 MI->addOperand(MachineOperand::CreateReg(Reg, true));
395 // Create the result registers for this node and add the result regs to
396 // the machine instruction.
398 const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
399 assert(RC && "Isn't a register operand!");
400 VRBase = RegInfo.createVirtualRegister(RC);
401 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
404 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
405 assert(isNew && "Node emitted out of order - early");
409 /// getVR - Return the virtual register corresponding to the specified result
410 /// of the specified node.
411 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
412 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
413 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
418 /// AddOperand - Add the specified operand to the specified machine instr. II
419 /// specifies the instruction information for the node, and IIOpNum is the
420 /// operand number (in the II) that we are adding. IIOpNum and II are used for
422 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
424 const TargetInstrDescriptor *II,
425 DenseMap<SDOperand, unsigned> &VRBaseMap) {
426 if (Op.isTargetOpcode()) {
427 // Note that this case is redundant with the final else block, but we
428 // include it because it is the most common and it makes the logic
430 assert(Op.getValueType() != MVT::Other &&
431 Op.getValueType() != MVT::Flag &&
432 "Chain and flag operands should occur at end of operand list!");
434 // Get/emit the operand.
435 unsigned VReg = getVR(Op, VRBaseMap);
436 const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
437 bool isOptDef = (IIOpNum < TID->numOperands)
438 ? (TID->OpInfo[IIOpNum].Flags & M_OPTIONAL_DEF_OPERAND) : false;
439 MI->addOperand(MachineOperand::CreateReg(VReg, isOptDef));
441 // Verify that it is right.
442 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
444 const TargetRegisterClass *RC =
445 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
446 assert(RC && "Don't have operand info for this instruction!");
447 const TargetRegisterClass *VRC = RegInfo.getRegClass(VReg);
449 cerr << "Register class of operand and regclass of use don't agree!\n";
451 cerr << "Operand = " << IIOpNum << "\n";
452 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
453 cerr << "MI = "; MI->print(cerr);
454 cerr << "VReg = " << VReg << "\n";
455 cerr << "VReg RegClass size = " << VRC->getSize()
456 << ", align = " << VRC->getAlignment() << "\n";
457 cerr << "Expected RegClass size = " << RC->getSize()
458 << ", align = " << RC->getAlignment() << "\n";
460 cerr << "Fatal error, aborting.\n";
464 } else if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
465 MI->addOperand(MachineOperand::CreateImm(C->getValue()));
466 } else if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Op)) {
467 MI->addOperand(MachineOperand::CreateReg(R->getReg(), false));
468 } else if (GlobalAddressSDNode *TGA = dyn_cast<GlobalAddressSDNode>(Op)) {
469 MI->addOperand(MachineOperand::CreateGA(TGA->getGlobal(),TGA->getOffset()));
470 } else if (BasicBlockSDNode *BB = dyn_cast<BasicBlockSDNode>(Op)) {
471 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
472 } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Op)) {
473 MI->addOperand(MachineOperand::CreateFI(FI->getIndex()));
474 } else if (JumpTableSDNode *JT = dyn_cast<JumpTableSDNode>(Op)) {
475 MI->addOperand(MachineOperand::CreateJTI(JT->getIndex()));
476 } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op)) {
477 int Offset = CP->getOffset();
478 unsigned Align = CP->getAlignment();
479 const Type *Type = CP->getType();
480 // MachineConstantPool wants an explicit alignment.
482 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
484 // Alignment of vector types. FIXME!
485 Align = TM.getTargetData()->getABITypeSize(Type);
486 Align = Log2_64(Align);
491 if (CP->isMachineConstantPoolEntry())
492 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
494 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
495 MI->addOperand(MachineOperand::CreateCPI(Idx, Offset));
496 } else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
497 MI->addOperand(MachineOperand::CreateES(ES->getSymbol()));
499 assert(Op.getValueType() != MVT::Other &&
500 Op.getValueType() != MVT::Flag &&
501 "Chain and flag operands should occur at end of operand list!");
502 unsigned VReg = getVR(Op, VRBaseMap);
503 MI->addOperand(MachineOperand::CreateReg(VReg, false));
505 // Verify that it is right.
506 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
508 const TargetRegisterClass *RC =
509 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
510 assert(RC && "Don't have operand info for this instruction!");
511 assert(RegInfo.getRegClass(VReg) == RC &&
512 "Register class of operand and regclass of use don't agree!");
518 // Returns the Register Class of a subregister
519 static const TargetRegisterClass *getSubRegisterRegClass(
520 const TargetRegisterClass *TRC,
522 // Pick the register class of the subregister
523 MRegisterInfo::regclass_iterator I = TRC->subregclasses_begin() + SubIdx-1;
524 assert(I < TRC->subregclasses_end() &&
525 "Invalid subregister index for register class");
529 static const TargetRegisterClass *getSuperregRegisterClass(
530 const TargetRegisterClass *TRC,
533 // Pick the register class of the superegister for this type
534 for (MRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
535 E = TRC->superregclasses_end(); I != E; ++I)
536 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
538 assert(false && "Couldn't find the register class");
542 /// EmitSubregNode - Generate machine code for subreg nodes.
544 void ScheduleDAG::EmitSubregNode(SDNode *Node,
545 DenseMap<SDOperand, unsigned> &VRBaseMap) {
547 unsigned Opc = Node->getTargetOpcode();
548 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
549 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
550 // the CopyToReg'd destination register instead of creating a new vreg.
551 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
554 if (Use->getOpcode() == ISD::CopyToReg &&
555 Use->getOperand(2).Val == Node) {
556 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
557 if (MRegisterInfo::isVirtualRegister(DestReg)) {
564 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
566 // TODO: If the node is a use of a CopyFromReg from a physical register
567 // fold the extract into the copy now
569 // Create the extract_subreg machine instruction.
571 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
573 // Figure out the register class to create for the destreg.
574 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
575 const TargetRegisterClass *TRC = RegInfo.getRegClass(VReg);
576 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
579 // Grab the destination register
580 const TargetRegisterClass *DRC = 0;
581 DRC = RegInfo.getRegClass(VRBase);
583 "Source subregister and destination must have the same class");
586 VRBase = RegInfo.createVirtualRegister(SRC);
589 // Add def, source, and subreg index
590 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
591 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
592 MI->addOperand(MachineOperand::CreateImm(SubIdx));
594 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
595 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
596 "Malformed insert_subreg node");
597 bool isUndefInput = (Node->getNumOperands() == 2);
602 SubReg = getVR(Node->getOperand(0), VRBaseMap);
603 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
605 SubReg = getVR(Node->getOperand(1), VRBaseMap);
606 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
609 // TODO: Add tracking info to SSARegMap of which vregs are subregs
610 // to allow coalescing in the allocator
612 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
613 // the CopyToReg'd destination register instead of creating a new vreg.
614 // If the CopyToReg'd destination register is physical, then fold the
615 // insert into the copy
616 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
619 if (Use->getOpcode() == ISD::CopyToReg &&
620 Use->getOperand(2).Val == Node) {
621 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
622 if (MRegisterInfo::isVirtualRegister(DestReg)) {
629 // Create the insert_subreg machine instruction.
631 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
633 // Figure out the register class to create for the destreg.
634 const TargetRegisterClass *TRC = 0;
636 TRC = RegInfo.getRegClass(VRBase);
638 TRC = getSuperregRegisterClass(RegInfo.getRegClass(SubReg), SubIdx,
639 Node->getValueType(0));
640 assert(TRC && "Couldn't determine register class for insert_subreg");
641 VRBase = RegInfo.createVirtualRegister(TRC); // Create the reg
644 MI->addOperand(MachineOperand::CreateReg(VRBase, true));
645 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
647 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
648 MI->addOperand(MachineOperand::CreateImm(SubIdx));
650 assert(0 && "Node is not a subreg insert or extract");
652 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
653 assert(isNew && "Node emitted out of order - early");
656 /// EmitNode - Generate machine code for an node and needed dependencies.
658 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
659 DenseMap<SDOperand, unsigned> &VRBaseMap) {
660 // If machine instruction
661 if (Node->isTargetOpcode()) {
662 unsigned Opc = Node->getTargetOpcode();
664 // Handle subreg insert/extract specially
665 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
666 Opc == TargetInstrInfo::INSERT_SUBREG) {
667 EmitSubregNode(Node, VRBaseMap);
671 const TargetInstrDescriptor &II = TII->get(Opc);
673 unsigned NumResults = CountResults(Node);
674 unsigned NodeOperands = CountOperands(Node);
675 unsigned NumMIOperands = NodeOperands + NumResults;
676 bool HasPhysRegOuts = (NumResults > II.numDefs) && II.ImplicitDefs;
678 assert((unsigned(II.numOperands) == NumMIOperands ||
679 HasPhysRegOuts || (II.Flags & M_VARIABLE_OPS)) &&
680 "#operands for dag node doesn't match .td file!");
683 // Create the new machine instruction.
684 MachineInstr *MI = new MachineInstr(II);
686 // Add result register values for things that are defined by this
689 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
691 // Emit all of the actual operands of this instruction, adding them to the
692 // instruction as appropriate.
693 for (unsigned i = 0; i != NodeOperands; ++i)
694 AddOperand(MI, Node->getOperand(i), i+II.numDefs, &II, VRBaseMap);
696 // Commute node if it has been determined to be profitable.
697 if (CommuteSet.count(Node)) {
698 MachineInstr *NewMI = TII->commuteInstruction(MI);
700 DOUT << "Sched: COMMUTING FAILED!\n";
702 DOUT << "Sched: COMMUTED TO: " << *NewMI;
710 // Now that we have emitted all operands, emit this instruction itself.
711 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
712 BB->insert(BB->end(), MI);
714 // Insert this instruction into the end of the basic block, potentially
715 // taking some custom action.
716 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
719 // Additional results must be an physical register def.
720 if (HasPhysRegOuts) {
721 for (unsigned i = II.numDefs; i < NumResults; ++i) {
722 unsigned Reg = II.ImplicitDefs[i - II.numDefs];
723 if (Node->hasAnyUseOfValue(i))
724 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
728 switch (Node->getOpcode()) {
733 assert(0 && "This target-independent node should have been selected!");
734 case ISD::EntryToken: // fall thru
735 case ISD::TokenFactor:
738 case ISD::CopyToReg: {
740 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
743 InReg = getVR(Node->getOperand(2), VRBaseMap);
744 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
745 if (InReg != DestReg) {// Coalesced away the copy?
746 const TargetRegisterClass *TRC = 0;
747 // Get the target register class
748 if (MRegisterInfo::isVirtualRegister(InReg))
749 TRC = RegInfo.getRegClass(InReg);
752 MRI->getPhysicalRegisterRegClass(Node->getOperand(2).getValueType(),
754 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC, TRC);
758 case ISD::CopyFromReg: {
759 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
760 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
763 case ISD::INLINEASM: {
764 unsigned NumOps = Node->getNumOperands();
765 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
766 --NumOps; // Ignore the flag operand.
768 // Create the inline asm machine instruction.
770 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
772 // Add the asm string as an external symbol operand.
774 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
775 MI->addOperand(MachineOperand::CreateES(AsmStr));
777 // Add all of the operand registers to the instruction.
778 for (unsigned i = 2; i != NumOps;) {
779 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
780 unsigned NumVals = Flags >> 3;
782 MI->addOperand(MachineOperand::CreateImm(Flags));
783 ++i; // Skip the ID value.
786 default: assert(0 && "Bad flags!");
787 case 1: // Use of register.
788 for (; NumVals; --NumVals, ++i) {
789 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
790 MI->addOperand(MachineOperand::CreateReg(Reg, false));
793 case 2: // Def of register.
794 for (; NumVals; --NumVals, ++i) {
795 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
796 MI->addOperand(MachineOperand::CreateReg(Reg, true));
799 case 3: { // Immediate.
800 for (; NumVals; --NumVals, ++i) {
801 if (ConstantSDNode *CS =
802 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
803 MI->addOperand(MachineOperand::CreateImm(CS->getValue()));
804 } else if (GlobalAddressSDNode *GA =
805 dyn_cast<GlobalAddressSDNode>(Node->getOperand(i))) {
806 MI->addOperand(MachineOperand::CreateGA(GA->getGlobal(),
809 BasicBlockSDNode *BB =cast<BasicBlockSDNode>(Node->getOperand(i));
810 MI->addOperand(MachineOperand::CreateMBB(BB->getBasicBlock()));
815 case 4: // Addressing mode.
816 // The addressing mode has been selected, just add all of the
817 // operands to the machine instruction.
818 for (; NumVals; --NumVals, ++i)
819 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
829 void ScheduleDAG::EmitNoop() {
830 TII->insertNoop(*BB, BB->end());
833 void ScheduleDAG::EmitCrossRCCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap) {
834 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
836 if (I->isCtrl) continue; // ignore chain preds
838 // Copy to physical register.
839 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->Dep);
840 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late");
841 // Find the destination physical register.
843 for (SUnit::const_succ_iterator II = SU->Succs.begin(),
844 EE = SU->Succs.end(); II != EE; ++II) {
850 assert(I->Reg && "Unknown physical register!");
851 MRI->copyRegToReg(*BB, BB->end(), Reg, VRI->second,
852 SU->CopyDstRC, SU->CopySrcRC);
854 // Copy from physical register.
855 assert(I->Reg && "Unknown physical register!");
856 unsigned VRBase = RegInfo.createVirtualRegister(SU->CopyDstRC);
857 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase));
858 assert(isNew && "Node emitted out of order - early");
859 MRI->copyRegToReg(*BB, BB->end(), VRBase, I->Reg,
860 SU->CopyDstRC, SU->CopySrcRC);
866 /// EmitSchedule - Emit the machine code in scheduled order.
867 void ScheduleDAG::EmitSchedule() {
868 // If this is the first basic block in the function, and if it has live ins
869 // that need to be copied into vregs, emit the copies into the top of the
870 // block before emitting the code for the block.
871 MachineFunction &MF = DAG.getMachineFunction();
872 if (&MF.front() == BB) {
873 for (MachineRegisterInfo::livein_iterator LI = RegInfo.livein_begin(),
874 E = RegInfo.livein_end(); LI != E; ++LI)
876 const TargetRegisterClass *RC = RegInfo.getRegClass(LI->second);
877 MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
883 // Finally, emit the code for all of the scheduled instructions.
884 DenseMap<SDOperand, unsigned> VRBaseMap;
885 DenseMap<SUnit*, unsigned> CopyVRBaseMap;
886 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
887 if (SUnit *SU = Sequence[i]) {
888 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
889 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
891 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
893 EmitCrossRCCopy(SU, CopyVRBaseMap);
895 // Null SUnit* is a noop.
901 /// dump - dump the schedule.
902 void ScheduleDAG::dumpSchedule() const {
903 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
904 if (SUnit *SU = Sequence[i])
907 cerr << "**** NOOP ****\n";
912 /// Run - perform scheduling.
914 MachineBasicBlock *ScheduleDAG::Run() {
919 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
920 /// a group of nodes flagged together.
921 void SUnit::dump(const SelectionDAG *G) const {
922 cerr << "SU(" << NodeNum << "): ";
926 cerr << "CROSS RC COPY ";
928 if (FlaggedNodes.size() != 0) {
929 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
931 FlaggedNodes[i]->dump(G);
937 void SUnit::dumpAll(const SelectionDAG *G) const {
940 cerr << " # preds left : " << NumPredsLeft << "\n";
941 cerr << " # succs left : " << NumSuccsLeft << "\n";
942 cerr << " Latency : " << Latency << "\n";
943 cerr << " Depth : " << Depth << "\n";
944 cerr << " Height : " << Height << "\n";
946 if (Preds.size() != 0) {
947 cerr << " Predecessors:\n";
948 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
954 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
960 if (Succs.size() != 0) {
961 cerr << " Successors:\n";
962 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
968 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";