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 "sched"
17 #include "llvm/CodeGen/ScheduleDAG.h"
18 #include "llvm/CodeGen/MachineConstantPool.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Target/TargetInstrInfo.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/MathExtras.h"
31 /// BuildSchedUnits - Build SUnits from the selection dag that we are input.
32 /// This SUnit graph is similar to the SelectionDAG, but represents flagged
33 /// together nodes with a single SUnit.
34 void ScheduleDAG::BuildSchedUnits() {
35 // Reserve entries in the vector for each of the SUnits we are creating. This
36 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get
38 SUnits.reserve(std::distance(DAG.allnodes_begin(), DAG.allnodes_end()));
40 const InstrItineraryData &InstrItins = TM.getInstrItineraryData();
42 for (SelectionDAG::allnodes_iterator NI = DAG.allnodes_begin(),
43 E = DAG.allnodes_end(); NI != E; ++NI) {
44 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate.
47 // If this node has already been processed, stop now.
48 if (SUnitMap[NI]) continue;
50 SUnit *NodeSUnit = NewSUnit(NI);
52 // See if anything is flagged to this node, if so, add them to flagged
53 // nodes. Nodes can have at most one flag input and one flag output. Flags
54 // are required the be the last operand and result of a node.
56 // Scan up, adding flagged preds to FlaggedNodes.
58 if (N->getNumOperands() &&
59 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
61 N = N->getOperand(N->getNumOperands()-1).Val;
62 NodeSUnit->FlaggedNodes.push_back(N);
63 SUnitMap[N] = NodeSUnit;
64 } while (N->getNumOperands() &&
65 N->getOperand(N->getNumOperands()-1).getValueType()== MVT::Flag);
66 std::reverse(NodeSUnit->FlaggedNodes.begin(),
67 NodeSUnit->FlaggedNodes.end());
70 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
71 // have a user of the flag operand.
73 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
74 SDOperand FlagVal(N, N->getNumValues()-1);
76 // There are either zero or one users of the Flag result.
77 bool HasFlagUse = false;
78 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
80 if (FlagVal.isOperand(*UI)) {
82 NodeSUnit->FlaggedNodes.push_back(N);
83 SUnitMap[N] = NodeSUnit;
87 if (!HasFlagUse) break;
90 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
93 SUnitMap[N] = NodeSUnit;
95 // Compute the latency for the node. We use the sum of the latencies for
96 // all nodes flagged together into this SUnit.
97 if (InstrItins.isEmpty()) {
98 // No latency information.
99 NodeSUnit->Latency = 1;
101 NodeSUnit->Latency = 0;
102 if (N->isTargetOpcode()) {
103 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
104 InstrStage *S = InstrItins.begin(SchedClass);
105 InstrStage *E = InstrItins.end(SchedClass);
107 NodeSUnit->Latency += S->Cycles;
109 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
110 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
111 if (FNode->isTargetOpcode()) {
112 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
113 InstrStage *S = InstrItins.begin(SchedClass);
114 InstrStage *E = InstrItins.end(SchedClass);
116 NodeSUnit->Latency += S->Cycles;
122 // Pass 2: add the preds, succs, etc.
123 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
124 SUnit *SU = &SUnits[su];
125 SDNode *MainNode = SU->Node;
127 if (MainNode->isTargetOpcode()) {
128 unsigned Opc = MainNode->getTargetOpcode();
129 if (TII->isTwoAddrInstr(Opc))
130 SU->isTwoAddress = true;
131 if (TII->isCommutableInstr(Opc))
132 SU->isCommutable = true;
135 // Find all predecessors and successors of the group.
136 // Temporarily add N to make code simpler.
137 SU->FlaggedNodes.push_back(MainNode);
139 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
140 SDNode *N = SU->FlaggedNodes[n];
142 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
143 SDNode *OpN = N->getOperand(i).Val;
144 if (isPassiveNode(OpN)) continue; // Not scheduled.
145 SUnit *OpSU = SUnitMap[OpN];
146 assert(OpSU && "Node has no SUnit!");
147 if (OpSU == SU) continue; // In the same group.
149 MVT::ValueType OpVT = N->getOperand(i).getValueType();
150 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
151 bool isChain = OpVT == MVT::Other;
153 if (SU->addPred(OpSU, isChain)) {
158 SU->NumChainPredsLeft++;
161 if (OpSU->addSucc(SU, isChain)) {
164 OpSU->NumSuccsLeft++;
166 OpSU->NumChainSuccsLeft++;
172 // Remove MainNode from FlaggedNodes again.
173 SU->FlaggedNodes.pop_back();
179 static void CalculateDepths(SUnit &SU, unsigned Depth) {
180 if (SU.Depth == 0 || Depth > SU.Depth) {
182 for (SUnit::succ_iterator I = SU.Succs.begin(), E = SU.Succs.end();
184 CalculateDepths(*I->first, Depth+1);
188 void ScheduleDAG::CalculateDepths() {
189 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
190 ::CalculateDepths(*Entry, 0U);
191 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
192 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
193 ::CalculateDepths(SUnits[i], 0U);
197 static void CalculateHeights(SUnit &SU, unsigned Height) {
198 if (SU.Height == 0 || Height > SU.Height) {
200 for (SUnit::pred_iterator I = SU.Preds.begin(), E = SU.Preds.end();
202 CalculateHeights(*I->first, Height+1);
205 void ScheduleDAG::CalculateHeights() {
206 SUnit *Root = SUnitMap[DAG.getRoot().Val];
207 ::CalculateHeights(*Root, 0U);
210 /// CountResults - The results of target nodes have register or immediate
211 /// operands first, then an optional chain, and optional flag operands (which do
212 /// not go into the machine instrs.)
213 static unsigned CountResults(SDNode *Node) {
214 unsigned N = Node->getNumValues();
215 while (N && Node->getValueType(N - 1) == MVT::Flag)
217 if (N && Node->getValueType(N - 1) == MVT::Other)
218 --N; // Skip over chain result.
222 /// CountOperands The inputs to target nodes have any actual inputs first,
223 /// followed by an optional chain operand, then flag operands. Compute the
224 /// number of actual operands that will go into the machine instr.
225 static unsigned CountOperands(SDNode *Node) {
226 unsigned N = Node->getNumOperands();
227 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
229 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
230 --N; // Ignore chain if it exists.
234 static const TargetRegisterClass *getInstrOperandRegClass(
235 const MRegisterInfo *MRI,
236 const TargetInstrInfo *TII,
237 const TargetInstrDescriptor *II,
239 if (Op >= II->numOperands) {
240 assert((II->Flags & M_VARIABLE_OPS)&& "Invalid operand # of instruction");
243 const TargetOperandInfo &toi = II->OpInfo[Op];
244 return (toi.Flags & M_LOOK_UP_PTR_REG_CLASS)
245 ? TII->getPointerRegClass() : MRI->getRegClass(toi.RegClass);
248 static unsigned CreateVirtualRegisters(const MRegisterInfo *MRI,
252 const TargetInstrInfo *TII,
253 const TargetInstrDescriptor &II) {
254 // Create the result registers for this node and add the result regs to
255 // the machine instruction.
257 RegMap->createVirtualRegister(getInstrOperandRegClass(MRI, TII, &II, 0));
258 MI->addRegOperand(ResultReg, true);
259 for (unsigned i = 1; i != NumResults; ++i) {
260 const TargetRegisterClass *RC = getInstrOperandRegClass(MRI, TII, &II, i);
261 assert(RC && "Isn't a register operand!");
262 MI->addRegOperand(RegMap->createVirtualRegister(RC), true);
267 /// getVR - Return the virtual register corresponding to the specified result
268 /// of the specified node.
269 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
270 std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
271 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
272 return I->second + Op.ResNo;
276 /// AddOperand - Add the specified operand to the specified machine instr. II
277 /// specifies the instruction information for the node, and IIOpNum is the
278 /// operand number (in the II) that we are adding. IIOpNum and II are used for
280 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
282 const TargetInstrDescriptor *II,
283 std::map<SDNode*, unsigned> &VRBaseMap) {
284 if (Op.isTargetOpcode()) {
285 // Note that this case is redundant with the final else block, but we
286 // include it because it is the most common and it makes the logic
288 assert(Op.getValueType() != MVT::Other &&
289 Op.getValueType() != MVT::Flag &&
290 "Chain and flag operands should occur at end of operand list!");
292 // Get/emit the operand.
293 unsigned VReg = getVR(Op, VRBaseMap);
294 MI->addRegOperand(VReg, false);
296 // Verify that it is right.
297 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
299 const TargetRegisterClass *RC =
300 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
301 assert(RC && "Don't have operand info for this instruction!");
302 assert(RegMap->getRegClass(VReg) == RC &&
303 "Register class of operand and regclass of use don't agree!");
305 } else if (ConstantSDNode *C =
306 dyn_cast<ConstantSDNode>(Op)) {
307 MI->addImmOperand(C->getValue());
308 } else if (RegisterSDNode*R =
309 dyn_cast<RegisterSDNode>(Op)) {
310 MI->addRegOperand(R->getReg(), false);
311 } else if (GlobalAddressSDNode *TGA =
312 dyn_cast<GlobalAddressSDNode>(Op)) {
313 MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
314 } else if (BasicBlockSDNode *BB =
315 dyn_cast<BasicBlockSDNode>(Op)) {
316 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
317 } else if (FrameIndexSDNode *FI =
318 dyn_cast<FrameIndexSDNode>(Op)) {
319 MI->addFrameIndexOperand(FI->getIndex());
320 } else if (JumpTableSDNode *JT =
321 dyn_cast<JumpTableSDNode>(Op)) {
322 MI->addJumpTableIndexOperand(JT->getIndex());
323 } else if (ConstantPoolSDNode *CP =
324 dyn_cast<ConstantPoolSDNode>(Op)) {
325 int Offset = CP->getOffset();
326 unsigned Align = CP->getAlignment();
327 const Type *Type = CP->getType();
328 // MachineConstantPool wants an explicit alignment.
330 if (Type == Type::DoubleTy)
331 Align = 3; // always 8-byte align doubles.
333 Align = TM.getTargetData()->getTypeAlignmentShift(Type);
335 // Alignment of packed types. FIXME!
336 Align = TM.getTargetData()->getTypeSize(Type);
337 Align = Log2_64(Align);
343 if (CP->isMachineConstantPoolEntry())
344 Idx = ConstPool->getConstantPoolIndex(CP->getMachineCPVal(), Align);
346 Idx = ConstPool->getConstantPoolIndex(CP->getConstVal(), Align);
347 MI->addConstantPoolIndexOperand(Idx, Offset);
348 } else if (ExternalSymbolSDNode *ES =
349 dyn_cast<ExternalSymbolSDNode>(Op)) {
350 MI->addExternalSymbolOperand(ES->getSymbol());
352 assert(Op.getValueType() != MVT::Other &&
353 Op.getValueType() != MVT::Flag &&
354 "Chain and flag operands should occur at end of operand list!");
355 unsigned VReg = getVR(Op, VRBaseMap);
356 MI->addRegOperand(VReg, false);
358 // Verify that it is right.
359 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
361 const TargetRegisterClass *RC =
362 getInstrOperandRegClass(MRI, TII, II, IIOpNum);
363 assert(RC && "Don't have operand info for this instruction!");
364 assert(RegMap->getRegClass(VReg) == RC &&
365 "Register class of operand and regclass of use don't agree!");
372 /// EmitNode - Generate machine code for an node and needed dependencies.
374 void ScheduleDAG::EmitNode(SDNode *Node,
375 std::map<SDNode*, unsigned> &VRBaseMap) {
376 unsigned VRBase = 0; // First virtual register for node
378 // If machine instruction
379 if (Node->isTargetOpcode()) {
380 unsigned Opc = Node->getTargetOpcode();
381 const TargetInstrDescriptor &II = TII->get(Opc);
383 unsigned NumResults = CountResults(Node);
384 unsigned NodeOperands = CountOperands(Node);
385 unsigned NumMIOperands = NodeOperands + NumResults;
387 assert((unsigned(II.numOperands) == NumMIOperands ||
388 (II.Flags & M_VARIABLE_OPS)) &&
389 "#operands for dag node doesn't match .td file!");
392 // Create the new machine instruction.
393 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands);
395 // Add result register values for things that are defined by this
398 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
399 // the CopyToReg'd destination register instead of creating a new vreg.
400 if (NumResults == 1) {
401 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
404 if (Use->getOpcode() == ISD::CopyToReg &&
405 Use->getOperand(2).Val == Node) {
406 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
407 if (MRegisterInfo::isVirtualRegister(Reg)) {
409 MI->addRegOperand(Reg, true);
416 // Otherwise, create new virtual registers.
417 if (NumResults && VRBase == 0)
418 VRBase = CreateVirtualRegisters(MRI, MI, NumResults, RegMap, TII, II);
420 // Emit all of the actual operands of this instruction, adding them to the
421 // instruction as appropriate.
422 for (unsigned i = 0; i != NodeOperands; ++i)
423 AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
425 // Commute node if it has been determined to be profitable.
426 if (CommuteSet.count(Node)) {
427 MachineInstr *NewMI = TII->commuteInstruction(MI);
429 DEBUG(std::cerr << "Sched: COMMUTING FAILED!\n");
431 DEBUG(std::cerr << "Sched: COMMUTED TO: " << *NewMI);
439 // Now that we have emitted all operands, emit this instruction itself.
440 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
441 BB->insert(BB->end(), MI);
443 // Insert this instruction into the end of the basic block, potentially
444 // taking some custom action.
445 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
448 switch (Node->getOpcode()) {
453 assert(0 && "This target-independent node should have been selected!");
454 case ISD::EntryToken: // fall thru
455 case ISD::TokenFactor:
457 case ISD::CopyToReg: {
458 unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
459 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
460 if (InReg != DestReg) // Coalesced away the copy?
461 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
462 RegMap->getRegClass(InReg));
465 case ISD::CopyFromReg: {
466 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
467 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
468 VRBase = SrcReg; // Just use the input register directly!
472 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
473 // the CopyToReg'd destination register instead of creating a new vreg.
474 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
477 if (Use->getOpcode() == ISD::CopyToReg &&
478 Use->getOperand(2).Val == Node) {
479 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
480 if (MRegisterInfo::isVirtualRegister(DestReg)) {
487 // Figure out the register class to create for the destreg.
488 const TargetRegisterClass *TRC = 0;
490 TRC = RegMap->getRegClass(VRBase);
493 // Pick the register class of the right type that contains this physreg.
494 for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
495 E = MRI->regclass_end(); I != E; ++I)
496 if ((*I)->hasType(Node->getValueType(0)) &&
497 (*I)->contains(SrcReg)) {
501 assert(TRC && "Couldn't find register class for reg copy!");
503 // Create the reg, emit the copy.
504 VRBase = RegMap->createVirtualRegister(TRC);
506 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
509 case ISD::INLINEASM: {
510 unsigned NumOps = Node->getNumOperands();
511 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
512 --NumOps; // Ignore the flag operand.
514 // Create the inline asm machine instruction.
516 new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
518 // Add the asm string as an external symbol operand.
520 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
521 MI->addExternalSymbolOperand(AsmStr);
523 // Add all of the operand registers to the instruction.
524 for (unsigned i = 2; i != NumOps;) {
525 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
526 unsigned NumVals = Flags >> 3;
528 MI->addImmOperand(Flags);
529 ++i; // Skip the ID value.
532 default: assert(0 && "Bad flags!");
533 case 1: // Use of register.
534 for (; NumVals; --NumVals, ++i) {
535 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
536 MI->addRegOperand(Reg, false);
539 case 2: // Def of register.
540 for (; NumVals; --NumVals, ++i) {
541 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
542 MI->addRegOperand(Reg, true);
545 case 3: { // Immediate.
546 assert(NumVals == 1 && "Unknown immediate value!");
547 uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
548 MI->addImmOperand(Val);
552 case 4: // Addressing mode.
553 // The addressing mode has been selected, just add all of the
554 // operands to the machine instruction.
555 for (; NumVals; --NumVals, ++i)
556 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
565 assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
566 VRBaseMap[Node] = VRBase;
569 void ScheduleDAG::EmitNoop() {
570 TII->insertNoop(*BB, BB->end());
573 /// EmitSchedule - Emit the machine code in scheduled order.
574 void ScheduleDAG::EmitSchedule() {
575 // If this is the first basic block in the function, and if it has live ins
576 // that need to be copied into vregs, emit the copies into the top of the
577 // block before emitting the code for the block.
578 MachineFunction &MF = DAG.getMachineFunction();
579 if (&MF.front() == BB && MF.livein_begin() != MF.livein_end()) {
580 for (MachineFunction::livein_iterator LI = MF.livein_begin(),
581 E = MF.livein_end(); LI != E; ++LI)
583 MRI->copyRegToReg(*MF.begin(), MF.begin()->end(), LI->second,
584 LI->first, RegMap->getRegClass(LI->second));
588 // Finally, emit the code for all of the scheduled instructions.
589 std::map<SDNode*, unsigned> VRBaseMap;
590 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
591 if (SUnit *SU = Sequence[i]) {
592 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
593 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
594 EmitNode(SU->Node, VRBaseMap);
596 // Null SUnit* is a noop.
602 /// dump - dump the schedule.
603 void ScheduleDAG::dumpSchedule() const {
604 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
605 if (SUnit *SU = Sequence[i])
608 std::cerr << "**** NOOP ****\n";
613 /// Run - perform scheduling.
615 MachineBasicBlock *ScheduleDAG::Run() {
616 TII = TM.getInstrInfo();
617 MRI = TM.getRegisterInfo();
618 RegMap = BB->getParent()->getSSARegMap();
619 ConstPool = BB->getParent()->getConstantPool();
625 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
626 /// a group of nodes flagged together.
627 void SUnit::dump(const SelectionDAG *G) const {
628 std::cerr << "SU(" << NodeNum << "): ";
631 if (FlaggedNodes.size() != 0) {
632 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
634 FlaggedNodes[i]->dump(G);
640 void SUnit::dumpAll(const SelectionDAG *G) const {
643 std::cerr << " # preds left : " << NumPredsLeft << "\n";
644 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
645 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
646 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
647 std::cerr << " Latency : " << Latency << "\n";
648 std::cerr << " Depth : " << Depth << "\n";
649 std::cerr << " Height : " << Height << "\n";
651 if (Preds.size() != 0) {
652 std::cerr << " Predecessors:\n";
653 for (SUnit::const_succ_iterator I = Preds.begin(), E = Preds.end();
656 std::cerr << " ch #";
658 std::cerr << " val #";
659 std::cerr << I->first << "\n";
662 if (Succs.size() != 0) {
663 std::cerr << " Successors:\n";
664 for (SUnit::const_succ_iterator I = Succs.begin(), E = Succs.end();
667 std::cerr << " ch #";
669 std::cerr << " val #";
670 std::cerr << I->first << "\n";