ScheduleDAGSDNodes.cpp revision 47c144505b9be28ed22c626b3a407c11dba2fec5
1//===--- ScheduleDAGSDNodes.cpp - Implement the ScheduleDAGSDNodes class --===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This implements the ScheduleDAG class, which is a base class used by 11// scheduling implementation classes. 12// 13//===----------------------------------------------------------------------===// 14 15#define DEBUG_TYPE "pre-RA-sched" 16#include "SDNodeDbgValue.h" 17#include "ScheduleDAGSDNodes.h" 18#include "InstrEmitter.h" 19#include "llvm/CodeGen/SelectionDAG.h" 20#include "llvm/CodeGen/MachineInstrBuilder.h" 21#include "llvm/CodeGen/MachineRegisterInfo.h" 22#include "llvm/MC/MCInstrItineraries.h" 23#include "llvm/Target/TargetMachine.h" 24#include "llvm/Target/TargetInstrInfo.h" 25#include "llvm/Target/TargetLowering.h" 26#include "llvm/Target/TargetRegisterInfo.h" 27#include "llvm/Target/TargetSubtargetInfo.h" 28#include "llvm/ADT/DenseMap.h" 29#include "llvm/ADT/SmallPtrSet.h" 30#include "llvm/ADT/SmallSet.h" 31#include "llvm/ADT/SmallVector.h" 32#include "llvm/ADT/Statistic.h" 33#include "llvm/Support/CommandLine.h" 34#include "llvm/Support/Debug.h" 35#include "llvm/Support/raw_ostream.h" 36using namespace llvm; 37 38STATISTIC(LoadsClustered, "Number of loads clustered together"); 39 40// This allows latency based scheduler to notice high latency instructions 41// without a target itinerary. The choise if number here has more to do with 42// balancing scheduler heursitics than with the actual machine latency. 43static cl::opt<int> HighLatencyCycles( 44 "sched-high-latency-cycles", cl::Hidden, cl::init(10), 45 cl::desc("Roughly estimate the number of cycles that 'long latency'" 46 "instructions take for targets with no itinerary")); 47 48ScheduleDAGSDNodes::ScheduleDAGSDNodes(MachineFunction &mf) 49 : ScheduleDAG(mf), BB(0), DAG(0), 50 InstrItins(mf.getTarget().getInstrItineraryData()) {} 51 52/// Run - perform scheduling. 53/// 54void ScheduleDAGSDNodes::Run(SelectionDAG *dag, MachineBasicBlock *bb) { 55 BB = bb; 56 DAG = dag; 57 58 // Clear the scheduler's SUnit DAG. 59 ScheduleDAG::clearDAG(); 60 Sequence.clear(); 61 62 // Invoke the target's selection of scheduler. 63 Schedule(); 64} 65 66/// NewSUnit - Creates a new SUnit and return a ptr to it. 67/// 68SUnit *ScheduleDAGSDNodes::NewSUnit(SDNode *N) { 69#ifndef NDEBUG 70 const SUnit *Addr = 0; 71 if (!SUnits.empty()) 72 Addr = &SUnits[0]; 73#endif 74 SUnits.push_back(SUnit(N, (unsigned)SUnits.size())); 75 assert((Addr == 0 || Addr == &SUnits[0]) && 76 "SUnits std::vector reallocated on the fly!"); 77 SUnits.back().OrigNode = &SUnits.back(); 78 SUnit *SU = &SUnits.back(); 79 const TargetLowering &TLI = DAG->getTargetLoweringInfo(); 80 if (!N || 81 (N->isMachineOpcode() && 82 N->getMachineOpcode() == TargetOpcode::IMPLICIT_DEF)) 83 SU->SchedulingPref = Sched::None; 84 else 85 SU->SchedulingPref = TLI.getSchedulingPreference(N); 86 return SU; 87} 88 89SUnit *ScheduleDAGSDNodes::Clone(SUnit *Old) { 90 SUnit *SU = NewSUnit(Old->getNode()); 91 SU->OrigNode = Old->OrigNode; 92 SU->Latency = Old->Latency; 93 SU->isVRegCycle = Old->isVRegCycle; 94 SU->isCall = Old->isCall; 95 SU->isCallOp = Old->isCallOp; 96 SU->isTwoAddress = Old->isTwoAddress; 97 SU->isCommutable = Old->isCommutable; 98 SU->hasPhysRegDefs = Old->hasPhysRegDefs; 99 SU->hasPhysRegClobbers = Old->hasPhysRegClobbers; 100 SU->isScheduleHigh = Old->isScheduleHigh; 101 SU->isScheduleLow = Old->isScheduleLow; 102 SU->SchedulingPref = Old->SchedulingPref; 103 Old->isCloned = true; 104 return SU; 105} 106 107/// CheckForPhysRegDependency - Check if the dependency between def and use of 108/// a specified operand is a physical register dependency. If so, returns the 109/// register and the cost of copying the register. 110static void CheckForPhysRegDependency(SDNode *Def, SDNode *User, unsigned Op, 111 const TargetRegisterInfo *TRI, 112 const TargetInstrInfo *TII, 113 unsigned &PhysReg, int &Cost) { 114 if (Op != 2 || User->getOpcode() != ISD::CopyToReg) 115 return; 116 117 unsigned Reg = cast<RegisterSDNode>(User->getOperand(1))->getReg(); 118 if (TargetRegisterInfo::isVirtualRegister(Reg)) 119 return; 120 121 unsigned ResNo = User->getOperand(2).getResNo(); 122 if (Def->isMachineOpcode()) { 123 const MCInstrDesc &II = TII->get(Def->getMachineOpcode()); 124 if (ResNo >= II.getNumDefs() && 125 II.ImplicitDefs[ResNo - II.getNumDefs()] == Reg) { 126 PhysReg = Reg; 127 const TargetRegisterClass *RC = 128 TRI->getMinimalPhysRegClass(Reg, Def->getValueType(ResNo)); 129 Cost = RC->getCopyCost(); 130 } 131 } 132} 133 134static void AddGlue(SDNode *N, SDValue Glue, bool AddGlue, SelectionDAG *DAG) { 135 SmallVector<EVT, 4> VTs; 136 SDNode *GlueDestNode = Glue.getNode(); 137 138 // Don't add glue from a node to itself. 139 if (GlueDestNode == N) return; 140 141 // Don't add glue to something which already has glue. 142 if (N->getValueType(N->getNumValues() - 1) == MVT::Glue) return; 143 144 for (unsigned I = 0, E = N->getNumValues(); I != E; ++I) 145 VTs.push_back(N->getValueType(I)); 146 147 if (AddGlue) 148 VTs.push_back(MVT::Glue); 149 150 SmallVector<SDValue, 4> Ops; 151 for (unsigned I = 0, E = N->getNumOperands(); I != E; ++I) 152 Ops.push_back(N->getOperand(I)); 153 154 if (GlueDestNode) 155 Ops.push_back(Glue); 156 157 SDVTList VTList = DAG->getVTList(&VTs[0], VTs.size()); 158 MachineSDNode::mmo_iterator Begin = 0, End = 0; 159 MachineSDNode *MN = dyn_cast<MachineSDNode>(N); 160 161 // Store memory references. 162 if (MN) { 163 Begin = MN->memoperands_begin(); 164 End = MN->memoperands_end(); 165 } 166 167 DAG->MorphNodeTo(N, N->getOpcode(), VTList, &Ops[0], Ops.size()); 168 169 // Reset the memory references 170 if (MN) 171 MN->setMemRefs(Begin, End); 172} 173 174/// ClusterNeighboringLoads - Force nearby loads together by "gluing" them. 175/// This function finds loads of the same base and different offsets. If the 176/// offsets are not far apart (target specific), it add MVT::Glue inputs and 177/// outputs to ensure they are scheduled together and in order. This 178/// optimization may benefit some targets by improving cache locality. 179void ScheduleDAGSDNodes::ClusterNeighboringLoads(SDNode *Node) { 180 SDNode *Chain = 0; 181 unsigned NumOps = Node->getNumOperands(); 182 if (Node->getOperand(NumOps-1).getValueType() == MVT::Other) 183 Chain = Node->getOperand(NumOps-1).getNode(); 184 if (!Chain) 185 return; 186 187 // Look for other loads of the same chain. Find loads that are loading from 188 // the same base pointer and different offsets. 189 SmallPtrSet<SDNode*, 16> Visited; 190 SmallVector<int64_t, 4> Offsets; 191 DenseMap<long long, SDNode*> O2SMap; // Map from offset to SDNode. 192 bool Cluster = false; 193 SDNode *Base = Node; 194 for (SDNode::use_iterator I = Chain->use_begin(), E = Chain->use_end(); 195 I != E; ++I) { 196 SDNode *User = *I; 197 if (User == Node || !Visited.insert(User)) 198 continue; 199 int64_t Offset1, Offset2; 200 if (!TII->areLoadsFromSameBasePtr(Base, User, Offset1, Offset2) || 201 Offset1 == Offset2) 202 // FIXME: Should be ok if they addresses are identical. But earlier 203 // optimizations really should have eliminated one of the loads. 204 continue; 205 if (O2SMap.insert(std::make_pair(Offset1, Base)).second) 206 Offsets.push_back(Offset1); 207 O2SMap.insert(std::make_pair(Offset2, User)); 208 Offsets.push_back(Offset2); 209 if (Offset2 < Offset1) 210 Base = User; 211 Cluster = true; 212 } 213 214 if (!Cluster) 215 return; 216 217 // Sort them in increasing order. 218 std::sort(Offsets.begin(), Offsets.end()); 219 220 // Check if the loads are close enough. 221 SmallVector<SDNode*, 4> Loads; 222 unsigned NumLoads = 0; 223 int64_t BaseOff = Offsets[0]; 224 SDNode *BaseLoad = O2SMap[BaseOff]; 225 Loads.push_back(BaseLoad); 226 for (unsigned i = 1, e = Offsets.size(); i != e; ++i) { 227 int64_t Offset = Offsets[i]; 228 SDNode *Load = O2SMap[Offset]; 229 if (!TII->shouldScheduleLoadsNear(BaseLoad, Load, BaseOff, Offset,NumLoads)) 230 break; // Stop right here. Ignore loads that are further away. 231 Loads.push_back(Load); 232 ++NumLoads; 233 } 234 235 if (NumLoads == 0) 236 return; 237 238 // Cluster loads by adding MVT::Glue outputs and inputs. This also 239 // ensure they are scheduled in order of increasing addresses. 240 SDNode *Lead = Loads[0]; 241 AddGlue(Lead, SDValue(0, 0), true, DAG); 242 243 SDValue InGlue = SDValue(Lead, Lead->getNumValues() - 1); 244 for (unsigned I = 1, E = Loads.size(); I != E; ++I) { 245 bool OutGlue = I < E - 1; 246 SDNode *Load = Loads[I]; 247 248 AddGlue(Load, InGlue, OutGlue, DAG); 249 250 if (OutGlue) 251 InGlue = SDValue(Load, Load->getNumValues() - 1); 252 253 ++LoadsClustered; 254 } 255} 256 257/// ClusterNodes - Cluster certain nodes which should be scheduled together. 258/// 259void ScheduleDAGSDNodes::ClusterNodes() { 260 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(), 261 E = DAG->allnodes_end(); NI != E; ++NI) { 262 SDNode *Node = &*NI; 263 if (!Node || !Node->isMachineOpcode()) 264 continue; 265 266 unsigned Opc = Node->getMachineOpcode(); 267 const MCInstrDesc &MCID = TII->get(Opc); 268 if (MCID.mayLoad()) 269 // Cluster loads from "near" addresses into combined SUnits. 270 ClusterNeighboringLoads(Node); 271 } 272} 273 274void ScheduleDAGSDNodes::BuildSchedUnits() { 275 // During scheduling, the NodeId field of SDNode is used to map SDNodes 276 // to their associated SUnits by holding SUnits table indices. A value 277 // of -1 means the SDNode does not yet have an associated SUnit. 278 unsigned NumNodes = 0; 279 for (SelectionDAG::allnodes_iterator NI = DAG->allnodes_begin(), 280 E = DAG->allnodes_end(); NI != E; ++NI) { 281 NI->setNodeId(-1); 282 ++NumNodes; 283 } 284 285 // Reserve entries in the vector for each of the SUnits we are creating. This 286 // ensure that reallocation of the vector won't happen, so SUnit*'s won't get 287 // invalidated. 288 // FIXME: Multiply by 2 because we may clone nodes during scheduling. 289 // This is a temporary workaround. 290 SUnits.reserve(NumNodes * 2); 291 292 // Add all nodes in depth first order. 293 SmallVector<SDNode*, 64> Worklist; 294 SmallPtrSet<SDNode*, 64> Visited; 295 Worklist.push_back(DAG->getRoot().getNode()); 296 Visited.insert(DAG->getRoot().getNode()); 297 298 SmallVector<SUnit*, 8> CallSUnits; 299 while (!Worklist.empty()) { 300 SDNode *NI = Worklist.pop_back_val(); 301 302 // Add all operands to the worklist unless they've already been added. 303 for (unsigned i = 0, e = NI->getNumOperands(); i != e; ++i) 304 if (Visited.insert(NI->getOperand(i).getNode())) 305 Worklist.push_back(NI->getOperand(i).getNode()); 306 307 if (isPassiveNode(NI)) // Leaf node, e.g. a TargetImmediate. 308 continue; 309 310 // If this node has already been processed, stop now. 311 if (NI->getNodeId() != -1) continue; 312 313 SUnit *NodeSUnit = NewSUnit(NI); 314 315 // See if anything is glued to this node, if so, add them to glued 316 // nodes. Nodes can have at most one glue input and one glue output. Glue 317 // is required to be the last operand and result of a node. 318 319 // Scan up to find glued preds. 320 SDNode *N = NI; 321 while (N->getNumOperands() && 322 N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Glue) { 323 N = N->getOperand(N->getNumOperands()-1).getNode(); 324 assert(N->getNodeId() == -1 && "Node already inserted!"); 325 N->setNodeId(NodeSUnit->NodeNum); 326 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall()) 327 NodeSUnit->isCall = true; 328 } 329 330 // Scan down to find any glued succs. 331 N = NI; 332 while (N->getValueType(N->getNumValues()-1) == MVT::Glue) { 333 SDValue GlueVal(N, N->getNumValues()-1); 334 335 // There are either zero or one users of the Glue result. 336 bool HasGlueUse = false; 337 for (SDNode::use_iterator UI = N->use_begin(), E = N->use_end(); 338 UI != E; ++UI) 339 if (GlueVal.isOperandOf(*UI)) { 340 HasGlueUse = true; 341 assert(N->getNodeId() == -1 && "Node already inserted!"); 342 N->setNodeId(NodeSUnit->NodeNum); 343 N = *UI; 344 if (N->isMachineOpcode() && TII->get(N->getMachineOpcode()).isCall()) 345 NodeSUnit->isCall = true; 346 break; 347 } 348 if (!HasGlueUse) break; 349 } 350 351 if (NodeSUnit->isCall) 352 CallSUnits.push_back(NodeSUnit); 353 354 // Schedule zero-latency TokenFactor below any nodes that may increase the 355 // schedule height. Otherwise, ancestors of the TokenFactor may appear to 356 // have false stalls. 357 if (NI->getOpcode() == ISD::TokenFactor) 358 NodeSUnit->isScheduleLow = true; 359 360 // If there are glue operands involved, N is now the bottom-most node 361 // of the sequence of nodes that are glued together. 362 // Update the SUnit. 363 NodeSUnit->setNode(N); 364 assert(N->getNodeId() == -1 && "Node already inserted!"); 365 N->setNodeId(NodeSUnit->NodeNum); 366 367 // Compute NumRegDefsLeft. This must be done before AddSchedEdges. 368 InitNumRegDefsLeft(NodeSUnit); 369 370 // Assign the Latency field of NodeSUnit using target-provided information. 371 ComputeLatency(NodeSUnit); 372 } 373 374 // Find all call operands. 375 while (!CallSUnits.empty()) { 376 SUnit *SU = CallSUnits.pop_back_val(); 377 for (const SDNode *SUNode = SU->getNode(); SUNode; 378 SUNode = SUNode->getGluedNode()) { 379 if (SUNode->getOpcode() != ISD::CopyToReg) 380 continue; 381 SDNode *SrcN = SUNode->getOperand(2).getNode(); 382 if (isPassiveNode(SrcN)) continue; // Not scheduled. 383 SUnit *SrcSU = &SUnits[SrcN->getNodeId()]; 384 SrcSU->isCallOp = true; 385 } 386 } 387} 388 389void ScheduleDAGSDNodes::AddSchedEdges() { 390 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 391 392 // Check to see if the scheduler cares about latencies. 393 bool UnitLatencies = ForceUnitLatencies(); 394 395 // Pass 2: add the preds, succs, etc. 396 for (unsigned su = 0, e = SUnits.size(); su != e; ++su) { 397 SUnit *SU = &SUnits[su]; 398 SDNode *MainNode = SU->getNode(); 399 400 if (MainNode->isMachineOpcode()) { 401 unsigned Opc = MainNode->getMachineOpcode(); 402 const MCInstrDesc &MCID = TII->get(Opc); 403 for (unsigned i = 0; i != MCID.getNumOperands(); ++i) { 404 if (MCID.getOperandConstraint(i, MCOI::TIED_TO) != -1) { 405 SU->isTwoAddress = true; 406 break; 407 } 408 } 409 if (MCID.isCommutable()) 410 SU->isCommutable = true; 411 } 412 413 // Find all predecessors and successors of the group. 414 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) { 415 if (N->isMachineOpcode() && 416 TII->get(N->getMachineOpcode()).getImplicitDefs()) { 417 SU->hasPhysRegClobbers = true; 418 unsigned NumUsed = InstrEmitter::CountResults(N); 419 while (NumUsed != 0 && !N->hasAnyUseOfValue(NumUsed - 1)) 420 --NumUsed; // Skip over unused values at the end. 421 if (NumUsed > TII->get(N->getMachineOpcode()).getNumDefs()) 422 SU->hasPhysRegDefs = true; 423 } 424 425 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) { 426 SDNode *OpN = N->getOperand(i).getNode(); 427 if (isPassiveNode(OpN)) continue; // Not scheduled. 428 SUnit *OpSU = &SUnits[OpN->getNodeId()]; 429 assert(OpSU && "Node has no SUnit!"); 430 if (OpSU == SU) continue; // In the same group. 431 432 EVT OpVT = N->getOperand(i).getValueType(); 433 assert(OpVT != MVT::Glue && "Glued nodes should be in same sunit!"); 434 bool isChain = OpVT == MVT::Other; 435 436 unsigned PhysReg = 0; 437 int Cost = 1; 438 // Determine if this is a physical register dependency. 439 CheckForPhysRegDependency(OpN, N, i, TRI, TII, PhysReg, Cost); 440 assert((PhysReg == 0 || !isChain) && 441 "Chain dependence via physreg data?"); 442 // FIXME: See ScheduleDAGSDNodes::EmitCopyFromReg. For now, scheduler 443 // emits a copy from the physical register to a virtual register unless 444 // it requires a cross class copy (cost < 0). That means we are only 445 // treating "expensive to copy" register dependency as physical register 446 // dependency. This may change in the future though. 447 if (Cost >= 0 && !StressSched) 448 PhysReg = 0; 449 450 // If this is a ctrl dep, latency is 1. 451 unsigned OpLatency = isChain ? 1 : OpSU->Latency; 452 // Special-case TokenFactor chains as zero-latency. 453 if(isChain && OpN->getOpcode() == ISD::TokenFactor) 454 OpLatency = 0; 455 456 const SDep &dep = SDep(OpSU, isChain ? SDep::Order : SDep::Data, 457 OpLatency, PhysReg); 458 if (!isChain && !UnitLatencies) { 459 ComputeOperandLatency(OpN, N, i, const_cast<SDep &>(dep)); 460 ST.adjustSchedDependency(OpSU, SU, const_cast<SDep &>(dep)); 461 } 462 463 if (!SU->addPred(dep) && !dep.isCtrl() && OpSU->NumRegDefsLeft > 1) { 464 // Multiple register uses are combined in the same SUnit. For example, 465 // we could have a set of glued nodes with all their defs consumed by 466 // another set of glued nodes. Register pressure tracking sees this as 467 // a single use, so to keep pressure balanced we reduce the defs. 468 // 469 // We can't tell (without more book-keeping) if this results from 470 // glued nodes or duplicate operands. As long as we don't reduce 471 // NumRegDefsLeft to zero, we handle the common cases well. 472 --OpSU->NumRegDefsLeft; 473 } 474 } 475 } 476 } 477} 478 479/// BuildSchedGraph - Build the SUnit graph from the selection dag that we 480/// are input. This SUnit graph is similar to the SelectionDAG, but 481/// excludes nodes that aren't interesting to scheduling, and represents 482/// glued together nodes with a single SUnit. 483void ScheduleDAGSDNodes::BuildSchedGraph(AliasAnalysis *AA) { 484 // Cluster certain nodes which should be scheduled together. 485 ClusterNodes(); 486 // Populate the SUnits array. 487 BuildSchedUnits(); 488 // Compute all the scheduling dependencies between nodes. 489 AddSchedEdges(); 490} 491 492// Initialize NumNodeDefs for the current Node's opcode. 493void ScheduleDAGSDNodes::RegDefIter::InitNodeNumDefs() { 494 // Check for phys reg copy. 495 if (!Node) 496 return; 497 498 if (!Node->isMachineOpcode()) { 499 if (Node->getOpcode() == ISD::CopyFromReg) 500 NodeNumDefs = 1; 501 else 502 NodeNumDefs = 0; 503 return; 504 } 505 unsigned POpc = Node->getMachineOpcode(); 506 if (POpc == TargetOpcode::IMPLICIT_DEF) { 507 // No register need be allocated for this. 508 NodeNumDefs = 0; 509 return; 510 } 511 unsigned NRegDefs = SchedDAG->TII->get(Node->getMachineOpcode()).getNumDefs(); 512 // Some instructions define regs that are not represented in the selection DAG 513 // (e.g. unused flags). See tMOVi8. Make sure we don't access past NumValues. 514 NodeNumDefs = std::min(Node->getNumValues(), NRegDefs); 515 DefIdx = 0; 516} 517 518// Construct a RegDefIter for this SUnit and find the first valid value. 519ScheduleDAGSDNodes::RegDefIter::RegDefIter(const SUnit *SU, 520 const ScheduleDAGSDNodes *SD) 521 : SchedDAG(SD), Node(SU->getNode()), DefIdx(0), NodeNumDefs(0) { 522 InitNodeNumDefs(); 523 Advance(); 524} 525 526// Advance to the next valid value defined by the SUnit. 527void ScheduleDAGSDNodes::RegDefIter::Advance() { 528 for (;Node;) { // Visit all glued nodes. 529 for (;DefIdx < NodeNumDefs; ++DefIdx) { 530 if (!Node->hasAnyUseOfValue(DefIdx)) 531 continue; 532 ValueType = Node->getValueType(DefIdx); 533 ++DefIdx; 534 return; // Found a normal regdef. 535 } 536 Node = Node->getGluedNode(); 537 if (Node == NULL) { 538 return; // No values left to visit. 539 } 540 InitNodeNumDefs(); 541 } 542} 543 544void ScheduleDAGSDNodes::InitNumRegDefsLeft(SUnit *SU) { 545 assert(SU->NumRegDefsLeft == 0 && "expect a new node"); 546 for (RegDefIter I(SU, this); I.IsValid(); I.Advance()) { 547 assert(SU->NumRegDefsLeft < USHRT_MAX && "overflow is ok but unexpected"); 548 ++SU->NumRegDefsLeft; 549 } 550} 551 552void ScheduleDAGSDNodes::ComputeLatency(SUnit *SU) { 553 SDNode *N = SU->getNode(); 554 555 // TokenFactor operands are considered zero latency, and some schedulers 556 // (e.g. Top-Down list) may rely on the fact that operand latency is nonzero 557 // whenever node latency is nonzero. 558 if (N && N->getOpcode() == ISD::TokenFactor) { 559 SU->Latency = 0; 560 return; 561 } 562 563 // Check to see if the scheduler cares about latencies. 564 if (ForceUnitLatencies()) { 565 SU->Latency = 1; 566 return; 567 } 568 569 if (!InstrItins || InstrItins->isEmpty()) { 570 if (N && N->isMachineOpcode() && 571 TII->isHighLatencyDef(N->getMachineOpcode())) 572 SU->Latency = HighLatencyCycles; 573 else 574 SU->Latency = 1; 575 return; 576 } 577 578 // Compute the latency for the node. We use the sum of the latencies for 579 // all nodes glued together into this SUnit. 580 SU->Latency = 0; 581 for (SDNode *N = SU->getNode(); N; N = N->getGluedNode()) 582 if (N->isMachineOpcode()) 583 SU->Latency += TII->getInstrLatency(InstrItins, N); 584} 585 586void ScheduleDAGSDNodes::ComputeOperandLatency(SDNode *Def, SDNode *Use, 587 unsigned OpIdx, SDep& dep) const{ 588 // Check to see if the scheduler cares about latencies. 589 if (ForceUnitLatencies()) 590 return; 591 592 if (dep.getKind() != SDep::Data) 593 return; 594 595 unsigned DefIdx = Use->getOperand(OpIdx).getResNo(); 596 if (Use->isMachineOpcode()) 597 // Adjust the use operand index by num of defs. 598 OpIdx += TII->get(Use->getMachineOpcode()).getNumDefs(); 599 int Latency = TII->getOperandLatency(InstrItins, Def, DefIdx, Use, OpIdx); 600 if (Latency > 1 && Use->getOpcode() == ISD::CopyToReg && 601 !BB->succ_empty()) { 602 unsigned Reg = cast<RegisterSDNode>(Use->getOperand(1))->getReg(); 603 if (TargetRegisterInfo::isVirtualRegister(Reg)) 604 // This copy is a liveout value. It is likely coalesced, so reduce the 605 // latency so not to penalize the def. 606 // FIXME: need target specific adjustment here? 607 Latency = (Latency > 1) ? Latency - 1 : 1; 608 } 609 if (Latency >= 0) 610 dep.setLatency(Latency); 611} 612 613void ScheduleDAGSDNodes::dumpNode(const SUnit *SU) const { 614 if (!SU->getNode()) { 615 dbgs() << "PHYS REG COPY\n"; 616 return; 617 } 618 619 SU->getNode()->dump(DAG); 620 dbgs() << "\n"; 621 SmallVector<SDNode *, 4> GluedNodes; 622 for (SDNode *N = SU->getNode()->getGluedNode(); N; N = N->getGluedNode()) 623 GluedNodes.push_back(N); 624 while (!GluedNodes.empty()) { 625 dbgs() << " "; 626 GluedNodes.back()->dump(DAG); 627 dbgs() << "\n"; 628 GluedNodes.pop_back(); 629 } 630} 631 632void ScheduleDAGSDNodes::dumpSchedule() const { 633 for (unsigned i = 0, e = Sequence.size(); i != e; i++) { 634 if (SUnit *SU = Sequence[i]) 635 SU->dump(this); 636 else 637 dbgs() << "**** NOOP ****\n"; 638 } 639} 640 641#ifndef NDEBUG 642/// VerifyScheduledSequence - Verify that all SUnits were scheduled and that 643/// their state is consistent with the nodes listed in Sequence. 644/// 645void ScheduleDAGSDNodes::VerifyScheduledSequence(bool isBottomUp) { 646 unsigned ScheduledNodes = ScheduleDAG::VerifyScheduledDAG(isBottomUp); 647 unsigned Noops = 0; 648 for (unsigned i = 0, e = Sequence.size(); i != e; ++i) 649 if (!Sequence[i]) 650 ++Noops; 651 assert(Sequence.size() - Noops == ScheduledNodes && 652 "The number of nodes scheduled doesn't match the expected number!"); 653} 654#endif // NDEBUG 655 656namespace { 657 struct OrderSorter { 658 bool operator()(const std::pair<unsigned, MachineInstr*> &A, 659 const std::pair<unsigned, MachineInstr*> &B) { 660 return A.first < B.first; 661 } 662 }; 663} 664 665/// ProcessSDDbgValues - Process SDDbgValues associated with this node. 666static void ProcessSDDbgValues(SDNode *N, SelectionDAG *DAG, 667 InstrEmitter &Emitter, 668 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders, 669 DenseMap<SDValue, unsigned> &VRBaseMap, 670 unsigned Order) { 671 if (!N->getHasDebugValue()) 672 return; 673 674 // Opportunistically insert immediate dbg_value uses, i.e. those with source 675 // order number right after the N. 676 MachineBasicBlock *BB = Emitter.getBlock(); 677 MachineBasicBlock::iterator InsertPos = Emitter.getInsertPos(); 678 ArrayRef<SDDbgValue*> DVs = DAG->GetDbgValues(N); 679 for (unsigned i = 0, e = DVs.size(); i != e; ++i) { 680 if (DVs[i]->isInvalidated()) 681 continue; 682 unsigned DVOrder = DVs[i]->getOrder(); 683 if (!Order || DVOrder == ++Order) { 684 MachineInstr *DbgMI = Emitter.EmitDbgValue(DVs[i], VRBaseMap); 685 if (DbgMI) { 686 Orders.push_back(std::make_pair(DVOrder, DbgMI)); 687 BB->insert(InsertPos, DbgMI); 688 } 689 DVs[i]->setIsInvalidated(); 690 } 691 } 692} 693 694// ProcessSourceNode - Process nodes with source order numbers. These are added 695// to a vector which EmitSchedule uses to determine how to insert dbg_value 696// instructions in the right order. 697static void ProcessSourceNode(SDNode *N, SelectionDAG *DAG, 698 InstrEmitter &Emitter, 699 DenseMap<SDValue, unsigned> &VRBaseMap, 700 SmallVector<std::pair<unsigned, MachineInstr*>, 32> &Orders, 701 SmallSet<unsigned, 8> &Seen) { 702 unsigned Order = DAG->GetOrdering(N); 703 if (!Order || !Seen.insert(Order)) { 704 // Process any valid SDDbgValues even if node does not have any order 705 // assigned. 706 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, 0); 707 return; 708 } 709 710 MachineBasicBlock *BB = Emitter.getBlock(); 711 if (Emitter.getInsertPos() == BB->begin() || BB->back().isPHI()) { 712 // Did not insert any instruction. 713 Orders.push_back(std::make_pair(Order, (MachineInstr*)0)); 714 return; 715 } 716 717 Orders.push_back(std::make_pair(Order, prior(Emitter.getInsertPos()))); 718 ProcessSDDbgValues(N, DAG, Emitter, Orders, VRBaseMap, Order); 719} 720 721void ScheduleDAGSDNodes:: 722EmitPhysRegCopy(SUnit *SU, DenseMap<SUnit*, unsigned> &VRBaseMap, 723 MachineBasicBlock::iterator InsertPos) { 724 for (SUnit::const_pred_iterator I = SU->Preds.begin(), E = SU->Preds.end(); 725 I != E; ++I) { 726 if (I->isCtrl()) continue; // ignore chain preds 727 if (I->getSUnit()->CopyDstRC) { 728 // Copy to physical register. 729 DenseMap<SUnit*, unsigned>::iterator VRI = VRBaseMap.find(I->getSUnit()); 730 assert(VRI != VRBaseMap.end() && "Node emitted out of order - late"); 731 // Find the destination physical register. 732 unsigned Reg = 0; 733 for (SUnit::const_succ_iterator II = SU->Succs.begin(), 734 EE = SU->Succs.end(); II != EE; ++II) { 735 if (II->isCtrl()) continue; // ignore chain preds 736 if (II->getReg()) { 737 Reg = II->getReg(); 738 break; 739 } 740 } 741 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), Reg) 742 .addReg(VRI->second); 743 } else { 744 // Copy from physical register. 745 assert(I->getReg() && "Unknown physical register!"); 746 unsigned VRBase = MRI.createVirtualRegister(SU->CopyDstRC); 747 bool isNew = VRBaseMap.insert(std::make_pair(SU, VRBase)).second; 748 (void)isNew; // Silence compiler warning. 749 assert(isNew && "Node emitted out of order - early"); 750 BuildMI(*BB, InsertPos, DebugLoc(), TII->get(TargetOpcode::COPY), VRBase) 751 .addReg(I->getReg()); 752 } 753 break; 754 } 755} 756 757/// EmitSchedule - Emit the machine code in scheduled order. Return the new 758/// InsertPos and MachineBasicBlock that contains this insertion 759/// point. ScheduleDAGSDNodes holds a BB pointer for convenience, but this does 760/// not necessarily refer to returned BB. The emitter may split blocks. 761MachineBasicBlock *ScheduleDAGSDNodes:: 762EmitSchedule(MachineBasicBlock::iterator &InsertPos) { 763 InstrEmitter Emitter(BB, InsertPos); 764 DenseMap<SDValue, unsigned> VRBaseMap; 765 DenseMap<SUnit*, unsigned> CopyVRBaseMap; 766 SmallVector<std::pair<unsigned, MachineInstr*>, 32> Orders; 767 SmallSet<unsigned, 8> Seen; 768 bool HasDbg = DAG->hasDebugValues(); 769 770 // If this is the first BB, emit byval parameter dbg_value's. 771 if (HasDbg && BB->getParent()->begin() == MachineFunction::iterator(BB)) { 772 SDDbgInfo::DbgIterator PDI = DAG->ByvalParmDbgBegin(); 773 SDDbgInfo::DbgIterator PDE = DAG->ByvalParmDbgEnd(); 774 for (; PDI != PDE; ++PDI) { 775 MachineInstr *DbgMI= Emitter.EmitDbgValue(*PDI, VRBaseMap); 776 if (DbgMI) 777 BB->insert(InsertPos, DbgMI); 778 } 779 } 780 781 for (unsigned i = 0, e = Sequence.size(); i != e; i++) { 782 SUnit *SU = Sequence[i]; 783 if (!SU) { 784 // Null SUnit* is a noop. 785 TII->insertNoop(*Emitter.getBlock(), InsertPos); 786 continue; 787 } 788 789 // For pre-regalloc scheduling, create instructions corresponding to the 790 // SDNode and any glued SDNodes and append them to the block. 791 if (!SU->getNode()) { 792 // Emit a copy. 793 EmitPhysRegCopy(SU, CopyVRBaseMap, InsertPos); 794 continue; 795 } 796 797 SmallVector<SDNode *, 4> GluedNodes; 798 for (SDNode *N = SU->getNode()->getGluedNode(); N; 799 N = N->getGluedNode()) 800 GluedNodes.push_back(N); 801 while (!GluedNodes.empty()) { 802 SDNode *N = GluedNodes.back(); 803 Emitter.EmitNode(GluedNodes.back(), SU->OrigNode != SU, SU->isCloned, 804 VRBaseMap); 805 // Remember the source order of the inserted instruction. 806 if (HasDbg) 807 ProcessSourceNode(N, DAG, Emitter, VRBaseMap, Orders, Seen); 808 GluedNodes.pop_back(); 809 } 810 Emitter.EmitNode(SU->getNode(), SU->OrigNode != SU, SU->isCloned, 811 VRBaseMap); 812 // Remember the source order of the inserted instruction. 813 if (HasDbg) 814 ProcessSourceNode(SU->getNode(), DAG, Emitter, VRBaseMap, Orders, 815 Seen); 816 } 817 818 // Insert all the dbg_values which have not already been inserted in source 819 // order sequence. 820 if (HasDbg) { 821 MachineBasicBlock::iterator BBBegin = BB->getFirstNonPHI(); 822 823 // Sort the source order instructions and use the order to insert debug 824 // values. 825 std::sort(Orders.begin(), Orders.end(), OrderSorter()); 826 827 SDDbgInfo::DbgIterator DI = DAG->DbgBegin(); 828 SDDbgInfo::DbgIterator DE = DAG->DbgEnd(); 829 // Now emit the rest according to source order. 830 unsigned LastOrder = 0; 831 for (unsigned i = 0, e = Orders.size(); i != e && DI != DE; ++i) { 832 unsigned Order = Orders[i].first; 833 MachineInstr *MI = Orders[i].second; 834 // Insert all SDDbgValue's whose order(s) are before "Order". 835 if (!MI) 836 continue; 837 for (; DI != DE && 838 (*DI)->getOrder() >= LastOrder && (*DI)->getOrder() < Order; ++DI) { 839 if ((*DI)->isInvalidated()) 840 continue; 841 MachineInstr *DbgMI = Emitter.EmitDbgValue(*DI, VRBaseMap); 842 if (DbgMI) { 843 if (!LastOrder) 844 // Insert to start of the BB (after PHIs). 845 BB->insert(BBBegin, DbgMI); 846 else { 847 // Insert at the instruction, which may be in a different 848 // block, if the block was split by a custom inserter. 849 MachineBasicBlock::iterator Pos = MI; 850 MI->getParent()->insert(llvm::next(Pos), DbgMI); 851 } 852 } 853 } 854 LastOrder = Order; 855 } 856 // Add trailing DbgValue's before the terminator. FIXME: May want to add 857 // some of them before one or more conditional branches? 858 while (DI != DE) { 859 MachineBasicBlock *InsertBB = Emitter.getBlock(); 860 MachineBasicBlock::iterator Pos= Emitter.getBlock()->getFirstTerminator(); 861 if (!(*DI)->isInvalidated()) { 862 MachineInstr *DbgMI= Emitter.EmitDbgValue(*DI, VRBaseMap); 863 if (DbgMI) 864 InsertBB->insert(Pos, DbgMI); 865 } 866 ++DI; 867 } 868 } 869 870 InsertPos = Emitter.getInsertPos(); 871 return Emitter.getBlock(); 872} 873 874/// Return the basic block label. 875std::string ScheduleDAGSDNodes::getDAGName() const { 876 return "sunit-dag." + BB->getFullName(); 877} 878