1 //===---- ScheduleDAG.cpp - Implement the ScheduleDAG class ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by James M. Laskey and is distributed under the
6 // University of Illinois Open Source 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/SSARegMap.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"
31 /// getPhysicalRegisterRegClass - Returns the Register Class of a physical
33 static const TargetRegisterClass *getPhysicalRegisterRegClass(
34 const MRegisterInfo *MRI,
37 assert(MRegisterInfo::isPhysicalRegister(reg) &&
38 "reg must be a physical register");
39 // Pick the register class of the right type that contains this physreg.
40 for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
41 E = MRI->regclass_end(); I != E; ++I)
42 if ((*I)->hasType(VT) && (*I)->contains(reg))
44 assert(false && "Couldn't find the register class");
49 /// CheckForPhysRegDependency - Check if the dependency between def and use of
50 /// a specified operand is a physical register dependency. If so, returns the
51 /// register and the cost of copying the register.
52 static void CheckForPhysRegDependency(SDNode *Def, SDNode *Use, unsigned Op,
53 const MRegisterInfo *MRI,
54 const TargetInstrInfo *TII,
55 unsigned &PhysReg, int &Cost) {
56 if (Op != 2 || Use->getOpcode() != ISD::CopyToReg)
59 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
60 if (MRegisterInfo::isVirtualRegister(Reg))
63 unsigned ResNo = Use->getOperand(2).ResNo;
64 if (Def->isTargetOpcode()) {
65 const TargetInstrDescriptor &II = TII->get(Def->getTargetOpcode());
66 if (ResNo >= II.numDefs &&
67 II.ImplicitDefs[ResNo - II.numDefs] == Reg) {
69 const TargetRegisterClass *RC =
70 getPhysicalRegisterRegClass(MRI, Def->getValueType(ResNo), Reg);
71 Cost = RC->getCopyCost();
76 SUnit *ScheduleDAG::Clone(SUnit *Old) {
77 SUnit *SU = NewSUnit(Old->Node);
78 for (unsigned i = 0, e = SU->FlaggedNodes.size(); i != e; ++i)
79 SU->FlaggedNodes.push_back(SU->FlaggedNodes[i]);
80 SU->InstanceNo = SUnitMap[Old->Node].size();
81 SU->Latency = Old->Latency;
82 SU->isTwoAddress = Old->isTwoAddress;
83 SU->isCommutable = Old->isCommutable;
84 SU->hasImplicitDefs = Old->hasImplicitDefs;
85 SUnitMap[Old->Node].push_back(SU);
89 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
90 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
91 /// together nodes with a single SUnit.
92 void ScheduleDAG::BuildSchedUnits() {
93 // Reserve entries in the vector for each of the SUnits we are creating. This
94 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
96 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
98 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
100 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
101 E = DAG.allnodes_end(); NI != E; ++NI) {
102 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
105 // If this node has already been processed, stop now.
106 if (SUnitMap[NI].size()) continue;
108 SUnit *NodeSUnit = NewSUnit(NI);
110 // See if anything is flagged to this node, if so, add them to flagged
111 // nodes. Nodes can have at most one flag input and one flag output. Flags
112 // are required the be the last operand and result of a node.
114 // Scan up, adding flagged preds to FlaggedNodes.
116 if (N->getNumOperands() &&
117 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
119 N = N->getOperand(N->getNumOperands()-1).Val;
120 NodeSUnit->FlaggedNodes.push_back(N);
121 SUnitMap[N].push_back(NodeSUnit);
122 } while (N->getNumOperands() &&
123 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
124 std::reverse(NodeSUnit->FlaggedNodes.begin(),
125 NodeSUnit->FlaggedNodes.end());
128 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
129 // have a user of the flag operand.
131 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
132 SDOperand FlagVal(N, N->getNumValues()-1);
134 // There are either zero or one users of the Flag result.
135 bool HasFlagUse = false;
136 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
138 if (FlagVal.isOperand(*UI)) {
140 NodeSUnit->FlaggedNodes.push_back(N);
141 SUnitMap[N].push_back(NodeSUnit);
145 if (!HasFlagUse) break;
148 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
151 SUnitMap[N].push_back(NodeSUnit);
153 // Compute the latency for the node. We use the sum of the latencies for
154 // all nodes flagged together into this SUnit.
155 if (InstrItins.isEmpty()) {
156 // No latency information.
157 NodeSUnit->Latency = 1;
159 NodeSUnit->Latency = 0;
160 if (N->isTargetOpcode()) {
161 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
162 InstrStage *S = InstrItins.begin(SchedClass);
163 InstrStage *E = InstrItins.end(SchedClass);
165 NodeSUnit->Latency += S->Cycles;
167 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
168 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
169 if (FNode->isTargetOpcode()) {
170 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
171 InstrStage *S = InstrItins.begin(SchedClass);
172 InstrStage *E = InstrItins.end(SchedClass);
174 NodeSUnit->Latency += S->Cycles;
180 // Pass 2: add the preds, succs, etc.
181 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
182 SUnit *SU = &SUnits[su];
183 SDNode *MainNode = SU->Node;
185 if (MainNode->isTargetOpcode()) {
186 unsigned Opc = MainNode->getTargetOpcode();
187 const TargetInstrDescriptor &TID = TII->get(Opc);
188 if (TID.ImplicitDefs)
189 SU->hasImplicitDefs = true;
190 for (unsigned i = 0; i != TID.numOperands; ++i) {
191 if (TID.getOperandConstraint(i, TOI::TIED_TO) != -1) {
192 SU->isTwoAddress = true;
196 if (TID.Flags & M_COMMUTABLE)
197 SU->isCommutable = true;
200 // Find all predecessors and successors of the group.
201 // Temporarily add N to make code simpler.
202 SU->FlaggedNodes.push_back(MainNode);
204 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
205 SDNode *N = SU->FlaggedNodes[n];
206 if (N->isTargetOpcode() && TII->getImplicitDefs(N->getTargetOpcode()))
207 SU->hasImplicitDefs = true;
209 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
210 SDNode *OpN = N->getOperand(i).Val;
211 if (isPassiveNode(OpN)) continue; // Not scheduled.
212 SUnit *OpSU = SUnitMap[OpN].front();
213 assert(OpSU && "Node has no SUnit!");
214 if (OpSU == SU) continue; // In the same group.
216 MVT::ValueType OpVT = N->getOperand(i).getValueType();
217 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
218 bool isChain = OpVT == MVT::Other;
220 unsigned PhysReg = 0;
222 // Determine if this is a physical register dependency.
223 CheckForPhysRegDependency(OpN, N, i, MRI, TII, PhysReg, Cost);
224 SU->addPred(OpSU, isChain, false, PhysReg, Cost);
228 // Remove MainNode from FlaggedNodes again.
229 SU->FlaggedNodes.pop_back();
235 void ScheduleDAG::CalculateDepths() {
236 std::vector<std::pair<SUnit*, unsigned> > WorkList;
237 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
238 if (SUnits[i].Preds.size() == 0)
239 WorkList.push_back(std::make_pair(&SUnits[i], 0U));
241 while (!WorkList.empty()) {
242 SUnit *SU = WorkList.back().first;
243 unsigned Depth = WorkList.back().second;
245 if (SU->Depth == 0 || Depth > SU->Depth) {
247 for (SUnit::succ_iterator I = SU->Succs.begin(), E = SU->Succs.end();
249 WorkList.push_back(std::make_pair(I->Dep, Depth+1));
254 void ScheduleDAG::CalculateHeights() {
255 std::vector<std::pair<SUnit*, unsigned> > WorkList;
256 SUnit *Root = SUnitMap[DAG.getRoot().Val].front();
257 WorkList.push_back(std::make_pair(Root, 0U));
259 while (!WorkList.empty()) {
260 SUnit *SU = WorkList.back().first;
261 unsigned Height = WorkList.back().second;
263 if (SU->Height == 0 || Height > SU->Height) {
265 for (SUnit::pred_iterator I = SU->Preds.begin(), E = SU->Preds.end();
267 WorkList.push_back(std::make_pair(I->Dep, Height+1));
272 /// CountResults - The results of target nodes have register or immediate
273 /// operands first, then an optional chain, and optional flag operands (which do
274 /// not go into the machine instrs.)
275 unsigned ScheduleDAG::CountResults(SDNode *Node) {
276 unsigned N = Node->getNumValues();
277 while (N && Node->getValueType(N - 1) == MVT::Flag)
279 if (N && Node->getValueType(N - 1) == MVT::Other)
280 --N; // Skip over chain result.
284 /// CountOperands The inputs to target nodes have any actual inputs first,
285 /// followed by an optional chain operand, then flag operands. Compute the
286 /// number of actual operands that will go into the machine instr.
287 unsigned ScheduleDAG::CountOperands(SDNode *Node) {
288 unsigned N = Node->getNumOperands();
289 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
291 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
292 --N; // Ignore chain if it exists.
296 static const TargetRegisterClass *getInstrOperandRegClass(
297 const MRegisterInfo *MRI,
298 const TargetInstrInfo *TII,
299 const TargetInstrDescriptor *II,
301 if (Op >= II->numOperands) {
302 assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
305 const TargetOperandInfo &toi = II->OpInfo[Op];
306 return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
307 ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
310 void ScheduleDAG::EmitCopyFromReg(SDNode *Node, unsigned ResNo,
311 unsigned InstanceNo, unsigned SrcReg,
312 DenseMap<SDOperand, unsigned> &VRBaseMap) {
314 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
315 // Just use the input register directly!
317 VRBaseMap.erase(SDOperand(Node, ResNo));
318 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo),SrcReg));
319 assert(isNew && "Node emitted out of order - early");
323 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
324 // the CopyToReg'd destination register instead of creating a new vreg.
325 bool MatchReg = true;
326 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
330 if (Use->getOpcode() == ISD::CopyToReg &&
331 Use->getOperand(2).Val == Node &&
332 Use->getOperand(2).ResNo == ResNo) {
333 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
334 if (MRegisterInfo::isVirtualRegister(DestReg)) {
337 } else if (DestReg != SrcReg)
340 for (unsigned i = 0, e = Use->getNumOperands(); i != e; ++i) {
341 SDOperand Op = Use->getOperand(i);
344 MVT::ValueType VT = Node->getValueType(Op.ResNo);
345 if (VT != MVT::Other && VT != MVT::Flag)
354 const TargetRegisterClass *TRC = 0;
355 // Figure out the register class to create for the destreg.
357 TRC = RegMap->getRegClass(VRBase);
359 TRC = getPhysicalRegisterRegClass(MRI, Node->getValueType(ResNo), SrcReg);
361 // If all uses are reading from the src physical register and copying the
362 // register is either impossible or very expensive, then don't create a copy.
363 if (MatchReg && TRC->getCopyCost() < 0) {
366 // Create the reg, emit the copy.
367 VRBase = RegMap->createVirtualRegister(TRC);
368 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
372 VRBaseMap.erase(SDOperand(Node, ResNo));
373 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,ResNo), VRBase));
374 assert(isNew && "Node emitted out of order - early");
377 void ScheduleDAG::CreateVirtualRegisters(SDNode *Node,
379 const TargetInstrDescriptor &II,
380 DenseMap<SDOperand, unsigned> &VRBaseMap) {
381 for (unsigned i = 0; i < II.numDefs; ++i) {
382 // If the specific node value is only used by a CopyToReg and the dest reg
383 // is a vreg, use the CopyToReg'd destination register instead of creating
386 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
389 if (Use->getOpcode() == ISD::CopyToReg &&
390 Use->getOperand(2).Val == Node &&
391 Use->getOperand(2).ResNo == i) {
392 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
393 if (MRegisterInfo::isVirtualRegister(Reg)) {
395 MI->addRegOperand(Reg, true);
401 // Create the result registers for this node and add the result regs to
402 // the machine instruction.
404 const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
405 assert(RC && "Isn't a register operand!");
406 VRBase = RegMap->createVirtualRegister(RC);
407 MI->addRegOperand(VRBase, true);
410 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,i), VRBase));
411 assert(isNew && "Node emitted out of order - early");
415 /// getVR - Return the virtual register corresponding to the specified result
416 /// of the specified node.
417 static unsigned getVR(SDOperand Op, DenseMap<SDOperand, unsigned> &VRBaseMap) {
418 DenseMap<SDOperand, unsigned>::iterator I = VRBaseMap.find(Op);
419 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
424 /// AddOperand - Add the specified operand to the specified machine instr. II
425 /// specifies the instruction information for the node, and IIOpNum is the
426 /// operand number (in the II) that we are adding. IIOpNum and II are used for
428 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
430 const TargetInstrDescriptor *II,
431 DenseMap<SDOperand, unsigned> &VRBaseMap) {
432 if (Op.isTargetOpcode()) {
433 // Note that this case is redundant with the final else block, but we
434 // include it because it is the most common and it makes the logic
436 assert(Op.getValueType() != MVT::Other &&
437 Op.getValueType() != MVT::Flag &&
438 "Chain and flag operands should occur at end of operand list!");
440 // Get/emit the operand.
441 unsigned VReg = getVR(Op, VRBaseMap);
442 const TargetInstrDescriptor *TID = MI->getInstrDescriptor();
443 bool isOptDef = (IIOpNum < TID->numOperands)
444 ? (TID->OpInfo[IIOpNum].Flags & M_OPTIONAL_DEF_OPERAND) : false;
445 MI->addRegOperand(VReg, isOptDef);
447 // Verify that it is right.
448 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
450 const TargetRegisterClass *RC =
451 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
452 assert(RC && "Don't have operand info for this instruction!");
453 const TargetRegisterClass *VRC = RegMap->getRegClass(VReg);
455 cerr << "Register class of operand and regclass of use don't agree!\n";
457 cerr << "Operand = " << IIOpNum << "\n";
458 cerr << "Op->Val = "; Op.Val->dump(&DAG); cerr << "\n";
459 cerr << "MI = "; MI->print(cerr);
460 cerr << "VReg = " << VReg << "\n";
461 cerr << "VReg RegClass size = " << VRC->getSize()
462 << ", align = " << VRC->getAlignment() << "\n";
463 cerr << "Expected RegClass size = " << RC->getSize()
464 << ", align = " << RC->getAlignment() << "\n";
466 cerr << "Fatal error, aborting.\n";
470 } else if (ConstantSDNode *C =
471 dyn_cast<ConstantSDNode>(Op)) {
472 MI->addImmOperand(C->getValue());
473 } else if (RegisterSDNode *R =
474 dyn_cast<RegisterSDNode>(Op)) {
475 MI->addRegOperand(R->getReg(), false);
476 } else if (GlobalAddressSDNode *TGA =
477 dyn_cast<GlobalAddressSDNode>(Op)) {
478 MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
479 } else if (BasicBlockSDNode *BB =
480 dyn_cast<BasicBlockSDNode>(Op)) {
481 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
482 } else if (FrameIndexSDNode *FI =
483 dyn_cast<FrameIndexSDNode>(Op)) {
484 MI->addFrameIndexOperand(FI->getIndex());
485 } else if (JumpTableSDNode *JT =
486 dyn_cast<JumpTableSDNode>(Op)) {
487 MI->addJumpTableIndexOperand(JT->getIndex());
488 } else if (ConstantPoolSDNode *CP =
489 dyn_cast<ConstantPoolSDNode>(Op)) {
490 int Offset = CP->getOffset();
491 unsigned Align = CP->getAlignment();
492 const Type *Type = CP->getType();
493 // MachineConstantPool wants an explicit alignment.
495 Align = TM.getTargetData()->getPreferredTypeAlignmentShift(Type);
497 // Alignment of vector types. FIXME!
498 Align = TM.getTargetData()->getTypeSize(Type);
499 Align = Log2_64(Align);
504 if (CP->isMachineConstantPoolEntry())
505 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
507 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
508 MI->addConstantPoolIndexOperand(Idx, Offset);
509 } else if (ExternalSymbolSDNode *ES =
510 dyn_cast<ExternalSymbolSDNode>(Op)) {
511 MI->addExternalSymbolOperand(ES->getSymbol());
513 assert(Op.getValueType() != MVT::Other &&
514 Op.getValueType() != MVT::Flag &&
515 "Chain and flag operands should occur at end of operand list!");
516 unsigned VReg = getVR(Op, VRBaseMap);
517 MI->addRegOperand(VReg, false);
519 // Verify that it is right.
520 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
522 const TargetRegisterClass *RC =
523 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
524 assert(RC && "Don't have operand info for this instruction!");
525 assert(RegMap->getRegClass(VReg) == RC &&
526 "Register class of operand and regclass of use don't agree!");
532 // Returns the Register Class of a subregister
533 static const TargetRegisterClass *getSubRegisterRegClass(
534 const TargetRegisterClass *TRC,
536 // Pick the register class of the subregister
537 MRegisterInfo::regclass_iterator I = TRC->subregclasses_begin() + SubIdx-1;
538 assert(I < TRC->subregclasses_end() &&
539 "Invalid subregister index for register class");
543 static const TargetRegisterClass *getSuperregRegisterClass(
544 const TargetRegisterClass *TRC,
547 // Pick the register class of the superegister for this type
548 for (MRegisterInfo::regclass_iterator I = TRC->superregclasses_begin(),
549 E = TRC->superregclasses_end(); I != E; ++I)
550 if ((*I)->hasType(VT) && getSubRegisterRegClass(*I, SubIdx) == TRC)
552 assert(false && "Couldn't find the register class");
556 /// EmitSubregNode - Generate machine code for subreg nodes.
558 void ScheduleDAG::EmitSubregNode(SDNode *Node,
559 DenseMap<SDOperand, unsigned> &VRBaseMap) {
561 unsigned Opc = Node->getTargetOpcode();
562 if (Opc == TargetInstrInfo::EXTRACT_SUBREG) {
563 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
564 // the CopyToReg'd destination register instead of creating a new vreg.
565 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
568 if (Use->getOpcode() == ISD::CopyToReg &&
569 Use->getOperand(2).Val == Node) {
570 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
571 if (MRegisterInfo::isVirtualRegister(DestReg)) {
578 unsigned SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
580 // TODO: If the node is a use of a CopyFromReg from a physical register
581 // fold the extract into the copy now
583 // TODO: Add tracking info to SSARegMap of which vregs are subregs
584 // to allow coalescing in the allocator
586 // Create the extract_subreg machine instruction.
588 new MachineInstr(BB, TII->get(TargetInstrInfo::EXTRACT_SUBREG));
590 // Figure out the register class to create for the destreg.
591 unsigned VReg = getVR(Node->getOperand(0), VRBaseMap);
592 const TargetRegisterClass *TRC = RegMap->getRegClass(VReg);
593 const TargetRegisterClass *SRC = getSubRegisterRegClass(TRC, SubIdx);
596 // Grab the destination register
597 const TargetRegisterClass *DRC = 0;
598 DRC = RegMap->getRegClass(VRBase);
600 "Source subregister and destination must have the same class");
603 VRBase = RegMap->createVirtualRegister(SRC);
606 // Add def, source, and subreg index
607 MI->addRegOperand(VRBase, true);
608 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
609 MI->addImmOperand(SubIdx);
611 } else if (Opc == TargetInstrInfo::INSERT_SUBREG) {
612 assert((Node->getNumOperands() == 2 || Node->getNumOperands() == 3) &&
613 "Malformed insert_subreg node");
614 bool isUndefInput = (Node->getNumOperands() == 2);
619 SubReg = getVR(Node->getOperand(0), VRBaseMap);
620 SubIdx = cast<ConstantSDNode>(Node->getOperand(1))->getValue();
622 SubReg = getVR(Node->getOperand(1), VRBaseMap);
623 SubIdx = cast<ConstantSDNode>(Node->getOperand(2))->getValue();
626 // TODO: Add tracking info to SSARegMap of which vregs are subregs
627 // to allow coalescing in the allocator
629 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
630 // the CopyToReg'd destination register instead of creating a new vreg.
631 // If the CopyToReg'd destination register is physical, then fold the
632 // insert into the copy
633 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
636 if (Use->getOpcode() == ISD::CopyToReg &&
637 Use->getOperand(2).Val == Node) {
638 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
639 if (MRegisterInfo::isVirtualRegister(DestReg)) {
646 // Create the insert_subreg machine instruction.
648 new MachineInstr(BB, TII->get(TargetInstrInfo::INSERT_SUBREG));
650 // Figure out the register class to create for the destreg.
651 const TargetRegisterClass *TRC = 0;
653 TRC = RegMap->getRegClass(VRBase);
655 TRC = getSuperregRegisterClass(RegMap->getRegClass(SubReg),
657 Node->getValueType(0));
658 assert(TRC && "Couldn't determine register class for insert_subreg");
659 VRBase = RegMap->createVirtualRegister(TRC); // Create the reg
662 MI->addRegOperand(VRBase, true);
663 AddOperand(MI, Node->getOperand(0), 0, 0, VRBaseMap);
665 AddOperand(MI, Node->getOperand(1), 0, 0, VRBaseMap);
666 MI->addImmOperand(SubIdx);
668 assert(0 && "Node is not a subreg insert or extract");
670 bool isNew = VRBaseMap.insert(std::make_pair(SDOperand(Node,0), VRBase));
671 assert(isNew && "Node emitted out of order - early");
674 /// EmitNode - Generate machine code for an node and needed dependencies.
676 void ScheduleDAG::EmitNode(SDNode *Node, unsigned InstanceNo,
677 DenseMap<SDOperand, unsigned> &VRBaseMap) {
678 // If machine instruction
679 if (Node->isTargetOpcode()) {
680 unsigned Opc = Node->getTargetOpcode();
682 // Handle subreg insert/extract specially
683 if (Opc == TargetInstrInfo::EXTRACT_SUBREG ||
684 Opc == TargetInstrInfo::INSERT_SUBREG) {
685 EmitSubregNode(Node, VRBaseMap);
689 const TargetInstrDescriptor &II = TII->get(Opc);
691 unsigned NumResults = CountResults(Node);
692 unsigned NodeOperands = CountOperands(Node);
693 unsigned NumMIOperands = NodeOperands + NumResults;
694 bool HasPhysRegOuts = (NumResults > II.numDefs) && II.ImplicitDefs;
696 assert((unsigned(II.numOperands) == NumMIOperands ||
697 HasPhysRegOuts || (II.Flags & M_VARIABLE_OPS)) &&
698 "#operands for dag node doesn't match .td file!");
701 // Create the new machine instruction.
702 MachineInstr *MI = new MachineInstr(II);
704 // Add result register values for things that are defined by this
707 CreateVirtualRegisters(Node, MI, II, VRBaseMap);
709 // Emit all of the actual operands of this instruction, adding them to the
710 // instruction as appropriate.
711 for (unsigned i = 0; i != NodeOperands; ++i)
712 AddOperand(MI, Node->getOperand(i), i+II.numDefs, &II, VRBaseMap);
714 // Commute node if it has been determined to be profitable.
715 if (CommuteSet.count(Node)) {
716 MachineInstr *NewMI = TII->commuteInstruction(MI);
718 DOUT << "Sched: COMMUTING FAILED!\n";
720 DOUT << "Sched: COMMUTED TO: " << *NewMI;
728 // Now that we have emitted all operands, emit this instruction itself.
729 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
730 BB->insert(BB->end(), MI);
732 // Insert this instruction into the end of the basic block, potentially
733 // taking some custom action.
734 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
737 // Additional results must be an physical register def.
738 if (HasPhysRegOuts) {
739 for (unsigned i = II.numDefs; i < NumResults; ++i) {
740 unsigned Reg = II.ImplicitDefs[i - II.numDefs];
741 if (Node->hasAnyUseOfValue(i))
742 EmitCopyFromReg(Node, i, InstanceNo, Reg, VRBaseMap);
746 switch (Node->getOpcode()) {
751 assert(0 && "This target-independent node should have been selected!");
752 case ISD::EntryToken: // fall thru
753 case ISD::TokenFactor:
756 case ISD::CopyToReg: {
758 if (RegisterSDNode *R = dyn_cast<RegisterSDNode>(Node->getOperand(2)))
761 InReg = getVR(Node->getOperand(2), VRBaseMap);
762 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
763 if (InReg != DestReg) {// Coalesced away the copy?
764 const TargetRegisterClass *TRC = 0;
765 // Get the target register class
766 if (MRegisterInfo::isVirtualRegister(InReg))
767 TRC = RegMap->getRegClass(InReg);
769 TRC = getPhysicalRegisterRegClass(MRI,
770 Node->getOperand(2).getValueType(),
772 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg, TRC);
776 case ISD::CopyFromReg: {
777 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
778 EmitCopyFromReg(Node, 0, InstanceNo, SrcReg, VRBaseMap);
781 case ISD::INLINEASM: {
782 unsigned NumOps = Node->getNumOperands();
783 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
784 --NumOps; // Ignore the flag operand.
786 // Create the inline asm machine instruction.
788 new MachineInstr(BB, TII->get(TargetInstrInfo::INLINEASM));
790 // Add the asm string as an external symbol operand.
792 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
793 MI->addExternalSymbolOperand(AsmStr);
795 // Add all of the operand registers to the instruction.
796 for (unsigned i = 2; i != NumOps;) {
797 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
798 unsigned NumVals = Flags >> 3;
800 MI->addImmOperand(Flags);
801 ++i; // Skip the ID value.
804 default: assert(0 && "Bad flags!");
805 case 1: // Use of register.
806 for (; NumVals; --NumVals, ++i) {
807 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
808 MI->addRegOperand(Reg, false);
811 case 2: // Def of register.
812 for (; NumVals; --NumVals, ++i) {
813 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
814 MI->addRegOperand(Reg, true);
817 case 3: { // Immediate.
818 for (; NumVals; --NumVals, ++i) {
819 if (ConstantSDNode *CS =
820 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
821 MI->addImmOperand(CS->getValue());
823 GlobalAddressSDNode *GA =
824 cast<GlobalAddressSDNode>(Node->getOperand(i));
825 MI->addGlobalAddressOperand(GA->getGlobal(), GA->getOffset());
830 case 4: // Addressing mode.
831 // The addressing mode has been selected, just add all of the
832 // operands to the machine instruction.
833 for (; NumVals; --NumVals, ++i)
834 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
844 void ScheduleDAG::EmitNoop() {
845 TII->insertNoop(*BB, BB->end());
848 /// EmitSchedule - Emit the machine code in scheduled order.
849 void ScheduleDAG::EmitSchedule() {
850 // If this is the first basic block in the function, and if it has live ins
851 // that need to be copied into vregs, emit the copies into the top of the
852 // block before emitting the code for the block.
853 MachineFunction &MF = DAG.getMachineFunction();
854 if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
855 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
856 E = MF.livein_end(); LI != E; ++LI)
858 MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
859 LI->first, RegMap->getRegClass(LI->second));
863 // Finally, emit the code for all of the scheduled instructions.
864 DenseMap<SDOperand, unsigned> VRBaseMap;
865 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
866 if (SUnit *SU = Sequence[i]) {
867 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; ++j)
868 EmitNode(SU->FlaggedNodes[j], SU->InstanceNo, VRBaseMap);
869 EmitNode(SU->Node, SU->InstanceNo, VRBaseMap);
871 // Null SUnit* is a noop.
877 /// dump - dump the schedule.
878 void ScheduleDAG::dumpSchedule() const {
879 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
880 if (SUnit *SU = Sequence[i])
883 cerr << "**** NOOP ****\n";
888 /// Run - perform scheduling.
890 MachineBasicBlock *ScheduleDAG::Run() {
891 TII = TM.getInstrInfo();
892 MRI = TM.getRegisterInfo();
893 RegMap = BB->getParent()->getSSARegMap();
894 ConstPool = BB->getParent()->getConstantPool();
900 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
901 /// a group of nodes flagged together.
902 void SUnit::dump(const SelectionDAG *G) const {
903 cerr << "SU(" << NodeNum << "): ";
906 if (FlaggedNodes.size() != 0) {
907 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
909 FlaggedNodes[i]->dump(G);
915 void SUnit::dumpAll(const SelectionDAG *G) const {
918 cerr << " # preds left : " << NumPredsLeft << "\n";
919 cerr << " # succs left : " << NumSuccsLeft << "\n";
920 cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
921 cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
922 cerr << " Latency : " << Latency << "\n";
923 cerr << " Depth : " << Depth << "\n";
924 cerr << " Height : " << Height << "\n";
926 if (Preds.size() != 0) {
927 cerr << " Predecessors:\n";
928 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
934 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";
940 if (Succs.size() != 0) {
941 cerr << " Successors:\n";
942 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
948 cerr << I->Dep << " - SU(" << I->Dep->NodeNum << ")";