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 while (N->getNumOperands() &&
59 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag) {
60 N = N->getOperand(N->getNumOperands()-1).Val;
61 NodeSUnit->FlaggedNodes.push_back(N);
62 SUnitMap[N] = NodeSUnit;
65 // Scan down, adding this node and any flagged succs to FlaggedNodes if they
66 // have a user of the flag operand.
68 while (N->getValueType(N->getNumValues()-1) == MVT::Flag) {
69 SDOperand FlagVal(N, N->getNumValues()-1);
71 // There are either zero or one users of the Flag result.
72 bool HasFlagUse = false;
73 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end();
75 if (FlagVal.isOperand(*UI)) {
77 NodeSUnit->FlaggedNodes.push_back(N);
78 SUnitMap[N] = NodeSUnit;
82 if (!HasFlagUse) break;
85 // Now all flagged nodes are in FlaggedNodes and N is the bottom-most node.
88 SUnitMap[N] = NodeSUnit;
90 // Compute the latency for the node. We use the sum of the latencies for
91 // all nodes flagged together into this SUnit.
92 if (InstrItins.isEmpty()) {
93 // No latency information.
94 NodeSUnit->Latency = 1;
96 NodeSUnit->Latency = 0;
97 if (N->isTargetOpcode()) {
98 unsigned SchedClass = TII->getSchedClass(N->getTargetOpcode());
99 InstrStage *S = InstrItins.begin(SchedClass);
100 InstrStage *E = InstrItins.end(SchedClass);
102 NodeSUnit->Latency += S->Cycles;
104 for (unsigned i = 0, e = NodeSUnit->FlaggedNodes.size(); i != e; ++i) {
105 SDNode *FNode = NodeSUnit->FlaggedNodes[i];
106 if (FNode->isTargetOpcode()) {
107 unsigned SchedClass = TII->getSchedClass(FNode->getTargetOpcode());
108 InstrStage *S = InstrItins.begin(SchedClass);
109 InstrStage *E = InstrItins.end(SchedClass);
111 NodeSUnit->Latency += S->Cycles;
117 // Pass 2: add the preds, succs, etc.
118 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) {
119 SUnit *SU = &SUnits[su];
120 SDNode *MainNode = SU->Node;
122 if (MainNode->isTargetOpcode()) {
123 unsigned Opc = MainNode->getTargetOpcode();
124 if (TII->isTwoAddrInstr(Opc))
125 SU->isTwoAddress = true;
126 if (TII->isCommutableInstr(Opc))
127 SU->isCommutable = true;
130 // Find all predecessors and successors of the group.
131 // Temporarily add N to make code simpler.
132 SU->FlaggedNodes.push_back(MainNode);
134 for (unsigned n = 0, e = SU->FlaggedNodes.size(); n != e; ++n) {
135 SDNode *N = SU->FlaggedNodes[n];
137 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
138 SDNode *OpN = N->getOperand(i).Val;
139 if (isPassiveNode(OpN)) continue; // Not scheduled.
140 SUnit *OpSU = SUnitMap[OpN];
141 assert(OpSU && "Node has no SUnit!");
142 if (OpSU == SU) continue; // In the same group.
144 MVT::ValueType OpVT = N->getOperand(i).getValueType();
145 assert(OpVT != MVT::Flag && "Flagged nodes should be in same sunit!");
146 bool isChain = OpVT == MVT::Other;
148 if (SU->Preds.insert(std::make_pair(OpSU, isChain)).second) {
153 SU->NumChainPredsLeft++;
156 if (OpSU->Succs.insert(std::make_pair(SU, isChain)).second) {
159 OpSU->NumSuccsLeft++;
161 OpSU->NumChainSuccsLeft++;
167 // Remove MainNode from FlaggedNodes again.
168 SU->FlaggedNodes.pop_back();
174 static void CalculateDepths(SUnit *SU, unsigned Depth) {
175 if (SU->Depth == 0 || Depth > SU->Depth) {
177 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Succs.begin(),
178 E = SU->Succs.end(); I != E; ++I)
179 CalculateDepths(I->first, Depth+1);
183 void ScheduleDAG::CalculateDepths() {
184 SUnit *Entry = SUnitMap[DAG.getEntryNode().Val];
185 ::CalculateDepths(Entry, 0U);
186 for (unsigned i = 0, e = SUnits.size(); i != e; ++i)
187 if (SUnits[i].Preds.size() == 0 && &SUnits[i] != Entry) {
188 ::CalculateDepths(&SUnits[i], 0U);
192 static void CalculateHeights(SUnit *SU, unsigned Height) {
193 if (SU->Height == 0 || Height > SU->Height) {
195 for (std::set<std::pair<SUnit*, bool> >::iterator I = SU->Preds.begin(),
196 E = SU->Preds.end(); I != E; ++I)
197 CalculateHeights(I->first, Height+1);
200 void ScheduleDAG::CalculateHeights() {
201 SUnit *Root = SUnitMap[DAG.getRoot().Val];
202 ::CalculateHeights(Root, 0U);
205 /// CountResults - The results of target nodes have register or immediate
206 /// operands first, then an optional chain, and optional flag operands (which do
207 /// not go into the machine instrs.)
208 static unsigned CountResults(SDNode *Node) {
209 unsigned N = Node->getNumValues();
210 while (N && Node->getValueType(N - 1) == MVT::Flag)
212 if (N && Node->getValueType(N - 1) == MVT::Other)
213 --N; // Skip over chain result.
217 /// CountOperands The inputs to target nodes have any actual inputs first,
218 /// followed by an optional chain operand, then flag operands. Compute the
219 /// number of actual operands that will go into the machine instr.
220 static unsigned CountOperands(SDNode *Node) {
221 unsigned N = Node->getNumOperands();
222 while (N && Node->getOperand(N - 1).getValueType() == MVT::Flag)
224 if (N && Node->getOperand(N - 1).getValueType() == MVT::Other)
225 --N; // Ignore chain if it exists.
229 static unsigned CreateVirtualRegisters(MachineInstr *MI,
232 const TargetInstrDescriptor &II) {
233 // Create the result registers for this node and add the result regs to
234 // the machine instruction.
235 const TargetOperandInfo *OpInfo = II.OpInfo;
236 unsigned ResultReg = RegMap->createVirtualRegister(OpInfo[0].RegClass);
237 MI->addRegOperand(ResultReg, MachineOperand::Def);
238 for (unsigned i = 1; i != NumResults; ++i) {
239 assert(OpInfo[i].RegClass && "Isn't a register operand!");
240 MI->addRegOperand(RegMap->createVirtualRegister(OpInfo[i].RegClass),
241 MachineOperand::Def);
246 /// getVR - Return the virtual register corresponding to the specified result
247 /// of the specified node.
248 static unsigned getVR(SDOperand Op, std::map<SDNode*, unsigned> &VRBaseMap) {
249 std::map<SDNode*, unsigned>::iterator I = VRBaseMap.find(Op.Val);
250 assert(I != VRBaseMap.end() && "Node emitted out of order - late");
251 return I->second + Op.ResNo;
255 /// AddOperand - Add the specified operand to the specified machine instr. II
256 /// specifies the instruction information for the node, and IIOpNum is the
257 /// operand number (in the II) that we are adding. IIOpNum and II are used for
259 void ScheduleDAG::AddOperand(MachineInstr *MI, SDOperand Op,
261 const TargetInstrDescriptor *II,
262 std::map<SDNode*, unsigned> &VRBaseMap) {
263 if (Op.isTargetOpcode()) {
264 // Note that this case is redundant with the final else block, but we
265 // include it because it is the most common and it makes the logic
267 assert(Op.getValueType() != MVT::Other &&
268 Op.getValueType() != MVT::Flag &&
269 "Chain and flag operands should occur at end of operand list!");
271 // Get/emit the operand.
272 unsigned VReg = getVR(Op, VRBaseMap);
273 MI->addRegOperand(VReg, MachineOperand::Use);
275 // Verify that it is right.
276 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
278 assert(II->OpInfo[IIOpNum].RegClass &&
279 "Don't have operand info for this instruction!");
280 assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
281 "Register class of operand and regclass of use don't agree!");
283 } else if (ConstantSDNode *C =
284 dyn_cast<ConstantSDNode>(Op)) {
285 MI->addImmOperand(C->getValue());
286 } else if (RegisterSDNode*R =
287 dyn_cast<RegisterSDNode>(Op)) {
288 MI->addRegOperand(R->getReg(), MachineOperand::Use);
289 } else if (GlobalAddressSDNode *TGA =
290 dyn_cast<GlobalAddressSDNode>(Op)) {
291 MI->addGlobalAddressOperand(TGA->getGlobal(), TGA->getOffset());
292 } else if (BasicBlockSDNode *BB =
293 dyn_cast<BasicBlockSDNode>(Op)) {
294 MI->addMachineBasicBlockOperand(BB->getBasicBlock());
295 } else if (FrameIndexSDNode *FI =
296 dyn_cast<FrameIndexSDNode>(Op)) {
297 MI->addFrameIndexOperand(FI->getIndex());
298 } else if (JumpTableSDNode *JT =
299 dyn_cast<JumpTableSDNode>(Op)) {
300 MI->addJumpTableIndexOperand(JT->getIndex());
301 } else if (ConstantPoolSDNode *CP =
302 dyn_cast<ConstantPoolSDNode>(Op)) {
303 int Offset = CP->getOffset();
304 unsigned Align = CP->getAlignment();
305 // MachineConstantPool wants an explicit alignment.
307 if (CP->get()->getType() == Type::DoubleTy)
308 Align = 3; // always 8-byte align doubles.
310 Align = TM.getTargetData()
311 ->getTypeAlignmentShift(CP->get()->getType());
313 // Alignment of packed types. FIXME!
314 Align = TM.getTargetData()->getTypeSize(CP->get()->getType());
315 Align = Log2_64(Align);
320 unsigned Idx = ConstPool->getConstantPoolIndex(CP->get(), Align);
321 MI->addConstantPoolIndexOperand(Idx, Offset);
322 } else if (ExternalSymbolSDNode *ES =
323 dyn_cast<ExternalSymbolSDNode>(Op)) {
324 MI->addExternalSymbolOperand(ES->getSymbol());
326 assert(Op.getValueType() != MVT::Other &&
327 Op.getValueType() != MVT::Flag &&
328 "Chain and flag operands should occur at end of operand list!");
329 unsigned VReg = getVR(Op, VRBaseMap);
330 MI->addRegOperand(VReg, MachineOperand::Use);
332 // Verify that it is right.
333 assert(MRegisterInfo::isVirtualRegister(VReg) && "Not a vreg?");
335 assert(II->OpInfo[IIOpNum].RegClass &&
336 "Don't have operand info for this instruction!");
337 assert(RegMap->getRegClass(VReg) == II->OpInfo[IIOpNum].RegClass &&
338 "Register class of operand and regclass of use don't agree!");
345 /// EmitNode - Generate machine code for an node and needed dependencies.
347 void ScheduleDAG::EmitNode(SDNode *Node,
348 std::map<SDNode*, unsigned> &VRBaseMap) {
349 unsigned VRBase = 0; // First virtual register for node
351 // If machine instruction
352 if (Node->isTargetOpcode()) {
353 unsigned Opc = Node->getTargetOpcode();
354 const TargetInstrDescriptor &II = TII->get(Opc);
356 unsigned NumResults = CountResults(Node);
357 unsigned NodeOperands = CountOperands(Node);
358 unsigned NumMIOperands = NodeOperands + NumResults;
360 assert((unsigned(II.numOperands) == NumMIOperands || II.numOperands == -1)&&
361 "#operands for dag node doesn't match .td file!");
364 // Create the new machine instruction.
365 MachineInstr *MI = new MachineInstr(Opc, NumMIOperands);
367 // Add result register values for things that are defined by this
370 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
371 // the CopyToReg'd destination register instead of creating a new vreg.
372 if (NumResults == 1) {
373 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
376 if (Use->getOpcode() == ISD::CopyToReg &&
377 Use->getOperand(2).Val == Node) {
378 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
379 if (MRegisterInfo::isVirtualRegister(Reg)) {
381 MI->addRegOperand(Reg, MachineOperand::Def);
388 // Otherwise, create new virtual registers.
389 if (NumResults && VRBase == 0)
390 VRBase = CreateVirtualRegisters(MI, NumResults, RegMap, II);
392 // Emit all of the actual operands of this instruction, adding them to the
393 // instruction as appropriate.
394 for (unsigned i = 0; i != NodeOperands; ++i)
395 AddOperand(MI, Node->getOperand(i), i+NumResults, &II, VRBaseMap);
397 // Commute node if it has been determined to be profitable.
398 if (CommuteSet.count(Node)) {
399 MachineInstr *NewMI = TII->commuteInstruction(MI);
401 DEBUG(std::cerr << "Sched: COMMUTING FAILED!\n");
403 DEBUG(std::cerr << "Sched: COMMUTED TO: " << *NewMI);
408 // Now that we have emitted all operands, emit this instruction itself.
409 if ((II.Flags & M_USES_CUSTOM_DAG_SCHED_INSERTION) == 0) {
410 BB->insert(BB->end(), MI);
412 // Insert this instruction into the end of the basic block, potentially
413 // taking some custom action.
414 BB = DAG.getTargetLoweringInfo().InsertAtEndOfBasicBlock(MI, BB);
417 switch (Node->getOpcode()) {
420 assert(0 && "This target-independent node should have been selected!");
421 case ISD::EntryToken: // fall thru
422 case ISD::TokenFactor:
424 case ISD::CopyToReg: {
425 unsigned InReg = getVR(Node->getOperand(2), VRBaseMap);
426 unsigned DestReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
427 if (InReg != DestReg) // Coalesced away the copy?
428 MRI->copyRegToReg(*BB, BB->end(), DestReg, InReg,
429 RegMap->getRegClass(InReg));
432 case ISD::CopyFromReg: {
433 unsigned SrcReg = cast<RegisterSDNode>(Node->getOperand(1))->getReg();
434 if (MRegisterInfo::isVirtualRegister(SrcReg)) {
435 VRBase = SrcReg; // Just use the input register directly!
439 // If the node is only used by a CopyToReg and the dest reg is a vreg, use
440 // the CopyToReg'd destination register instead of creating a new vreg.
441 for (SDNode::use_iterator UI = Node->use_begin(), E = Node->use_end();
444 if (Use->getOpcode() == ISD::CopyToReg &&
445 Use->getOperand(2).Val == Node) {
446 unsigned DestReg = cast<RegisterSDNode>(Use->getOperand(1))->getReg();
447 if (MRegisterInfo::isVirtualRegister(DestReg)) {
454 // Figure out the register class to create for the destreg.
455 const TargetRegisterClass *TRC = 0;
457 TRC = RegMap->getRegClass(VRBase);
460 // Pick the register class of the right type that contains this physreg.
461 for (MRegisterInfo::regclass_iterator I = MRI->regclass_begin(),
462 E = MRI->regclass_end(); I != E; ++I)
463 if ((*I)->hasType(Node->getValueType(0)) &&
464 (*I)->contains(SrcReg)) {
468 assert(TRC && "Couldn't find register class for reg copy!");
470 // Create the reg, emit the copy.
471 VRBase = RegMap->createVirtualRegister(TRC);
473 MRI->copyRegToReg(*BB, BB->end(), VRBase, SrcReg, TRC);
476 case ISD::INLINEASM: {
477 unsigned NumOps = Node->getNumOperands();
478 if (Node->getOperand(NumOps-1).getValueType() == MVT::Flag)
479 --NumOps; // Ignore the flag operand.
481 // Create the inline asm machine instruction.
483 new MachineInstr(BB, TargetInstrInfo::INLINEASM, (NumOps-2)/2+1);
485 // Add the asm string as an external symbol operand.
487 cast<ExternalSymbolSDNode>(Node->getOperand(1))->getSymbol();
488 MI->addExternalSymbolOperand(AsmStr);
490 // Add all of the operand registers to the instruction.
491 for (unsigned i = 2; i != NumOps;) {
492 unsigned Flags = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
493 unsigned NumVals = Flags >> 3;
495 MI->addImmOperand(Flags);
496 ++i; // Skip the ID value.
499 default: assert(0 && "Bad flags!");
500 case 1: // Use of register.
501 for (; NumVals; --NumVals, ++i) {
502 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
503 MI->addRegOperand(Reg, MachineOperand::Use);
506 case 2: // Def of register.
507 for (; NumVals; --NumVals, ++i) {
508 unsigned Reg = cast<RegisterSDNode>(Node->getOperand(i))->getReg();
509 MI->addRegOperand(Reg, MachineOperand::Def);
512 case 3: { // Immediate.
513 assert(NumVals == 1 && "Unknown immediate value!");
514 uint64_t Val = cast<ConstantSDNode>(Node->getOperand(i))->getValue();
515 MI->addImmOperand(Val);
519 case 4: // Addressing mode.
520 // The addressing mode has been selected, just add all of the
521 // operands to the machine instruction.
522 for (; NumVals; --NumVals, ++i)
523 AddOperand(MI, Node->getOperand(i), 0, 0, VRBaseMap);
532 assert(!VRBaseMap.count(Node) && "Node emitted out of order - early");
533 VRBaseMap[Node] = VRBase;
536 void ScheduleDAG::EmitNoop() {
537 TII->insertNoop(*BB, BB->end());
540 /// EmitSchedule - Emit the machine code in scheduled order.
541 void ScheduleDAG::EmitSchedule() {
542 std::map<SDNode*, unsigned> VRBaseMap;
543 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
544 if (SUnit *SU = Sequence[i]) {
545 for (unsigned j = 0, ee = SU->FlaggedNodes.size(); j != ee; j++)
546 EmitNode(SU->FlaggedNodes[j], VRBaseMap);
547 EmitNode(SU->Node, VRBaseMap);
549 // Null SUnit* is a noop.
555 /// dump - dump the schedule.
556 void ScheduleDAG::dumpSchedule() const {
557 for (unsigned i = 0, e = Sequence.size(); i != e; i++) {
558 if (SUnit *SU = Sequence[i])
561 std::cerr << "**** NOOP ****\n";
566 /// Run - perform scheduling.
568 MachineBasicBlock *ScheduleDAG::Run() {
569 TII = TM.getInstrInfo();
570 MRI = TM.getRegisterInfo();
571 RegMap = BB->getParent()->getSSARegMap();
572 ConstPool = BB->getParent()->getConstantPool();
578 /// SUnit - Scheduling unit. It's an wrapper around either a single SDNode or
579 /// a group of nodes flagged together.
580 void SUnit::dump(const SelectionDAG *G) const {
581 std::cerr << "SU(" << NodeNum << "): ";
584 if (FlaggedNodes.size() != 0) {
585 for (unsigned i = 0, e = FlaggedNodes.size(); i != e; i++) {
587 FlaggedNodes[i]->dump(G);
593 void SUnit::dumpAll(const SelectionDAG *G) const {
596 std::cerr << " # preds left : " << NumPredsLeft << "\n";
597 std::cerr << " # succs left : " << NumSuccsLeft << "\n";
598 std::cerr << " # chain preds left : " << NumChainPredsLeft << "\n";
599 std::cerr << " # chain succs left : " << NumChainSuccsLeft << "\n";
600 std::cerr << " Latency : " << Latency << "\n";
601 std::cerr << " Depth : " << Depth << "\n";
602 std::cerr << " Height : " << Height << "\n";
604 if (Preds.size() != 0) {
605 std::cerr << " Predecessors:\n";
606 for (std::set<std::pair<SUnit*,bool> >::const_iterator I = Preds.begin(),
607 E = Preds.end(); I != E; ++I) {
611 std::cerr << " val ";
615 if (Succs.size() != 0) {
616 std::cerr << " Successors:\n";
617 for (std::set<std::pair<SUnit*, bool> >::const_iterator I = Succs.begin(),
618 E = Succs.end(); I != E; ++I) {
622 std::cerr << " val ";