1 //===---- ScheduleDAGInstrs.cpp - MachineInstr Rescheduling ---------------===// 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 ScheduleDAGInstrs class, which implements re-scheduling 11 // of MachineInstrs. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #define DEBUG_TYPE "sched-instrs" 16 #include "llvm/Operator.h" 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/ValueTracking.h" 19 #include "llvm/CodeGen/LiveIntervalAnalysis.h" 20 #include "llvm/CodeGen/MachineFunctionPass.h" 21 #include "llvm/CodeGen/MachineMemOperand.h" 22 #include "llvm/CodeGen/MachineRegisterInfo.h" 23 #include "llvm/CodeGen/PseudoSourceValue.h" 24 #include "llvm/CodeGen/RegisterPressure.h" 25 #include "llvm/CodeGen/ScheduleDAGILP.h" 26 #include "llvm/CodeGen/ScheduleDAGInstrs.h" 27 #include "llvm/MC/MCInstrItineraries.h" 28 #include "llvm/Target/TargetMachine.h" 29 #include "llvm/Target/TargetInstrInfo.h" 30 #include "llvm/Target/TargetRegisterInfo.h" 31 #include "llvm/Target/TargetSubtargetInfo.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/Format.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/ADT/SmallSet.h" 37 #include "llvm/ADT/SmallPtrSet.h" 38 using namespace llvm; 39 40 static cl::opt<bool> EnableAASchedMI("enable-aa-sched-mi", cl::Hidden, 41 cl::ZeroOrMore, cl::init(false), 42 cl::desc("Enable use of AA during MI GAD construction")); 43 44 ScheduleDAGInstrs::ScheduleDAGInstrs(MachineFunction &mf, 45 const MachineLoopInfo &mli, 46 const MachineDominatorTree &mdt, 47 bool IsPostRAFlag, 48 LiveIntervals *lis) 49 : ScheduleDAG(mf), MLI(mli), MDT(mdt), MFI(mf.getFrameInfo()), LIS(lis), 50 IsPostRA(IsPostRAFlag), CanHandleTerminators(false), FirstDbgValue(0) { 51 assert((IsPostRA || LIS) && "PreRA scheduling requires LiveIntervals"); 52 DbgValues.clear(); 53 assert(!(IsPostRA && MRI.getNumVirtRegs()) && 54 "Virtual registers must be removed prior to PostRA scheduling"); 55 56 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 57 SchedModel.init(*ST.getSchedModel(), &ST, TII); 58 } 59 60 /// getUnderlyingObjectFromInt - This is the function that does the work of 61 /// looking through basic ptrtoint+arithmetic+inttoptr sequences. 62 static const Value *getUnderlyingObjectFromInt(const Value *V) { 63 do { 64 if (const Operator *U = dyn_cast<Operator>(V)) { 65 // If we find a ptrtoint, we can transfer control back to the 66 // regular getUnderlyingObjectFromInt. 67 if (U->getOpcode() == Instruction::PtrToInt) 68 return U->getOperand(0); 69 // If we find an add of a constant or a multiplied value, it's 70 // likely that the other operand will lead us to the base 71 // object. We don't have to worry about the case where the 72 // object address is somehow being computed by the multiply, 73 // because our callers only care when the result is an 74 // identifiable object. 75 if (U->getOpcode() != Instruction::Add || 76 (!isa<ConstantInt>(U->getOperand(1)) && 77 Operator::getOpcode(U->getOperand(1)) != Instruction::Mul)) 78 return V; 79 V = U->getOperand(0); 80 } else { 81 return V; 82 } 83 assert(V->getType()->isIntegerTy() && "Unexpected operand type!"); 84 } while (1); 85 } 86 87 /// getUnderlyingObject - This is a wrapper around GetUnderlyingObject 88 /// and adds support for basic ptrtoint+arithmetic+inttoptr sequences. 89 static const Value *getUnderlyingObject(const Value *V) { 90 // First just call Value::getUnderlyingObject to let it do what it does. 91 do { 92 V = GetUnderlyingObject(V); 93 // If it found an inttoptr, use special code to continue climing. 94 if (Operator::getOpcode(V) != Instruction::IntToPtr) 95 break; 96 const Value *O = getUnderlyingObjectFromInt(cast<User>(V)->getOperand(0)); 97 // If that succeeded in finding a pointer, continue the search. 98 if (!O->getType()->isPointerTy()) 99 break; 100 V = O; 101 } while (1); 102 return V; 103 } 104 105 /// getUnderlyingObjectForInstr - If this machine instr has memory reference 106 /// information and it can be tracked to a normal reference to a known 107 /// object, return the Value for that object. Otherwise return null. 108 static const Value *getUnderlyingObjectForInstr(const MachineInstr *MI, 109 const MachineFrameInfo *MFI, 110 bool &MayAlias) { 111 MayAlias = true; 112 if (!MI->hasOneMemOperand() || 113 !(*MI->memoperands_begin())->getValue() || 114 (*MI->memoperands_begin())->isVolatile()) 115 return 0; 116 117 const Value *V = (*MI->memoperands_begin())->getValue(); 118 if (!V) 119 return 0; 120 121 V = getUnderlyingObject(V); 122 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) { 123 // For now, ignore PseudoSourceValues which may alias LLVM IR values 124 // because the code that uses this function has no way to cope with 125 // such aliases. 126 if (PSV->isAliased(MFI)) 127 return 0; 128 129 MayAlias = PSV->mayAlias(MFI); 130 return V; 131 } 132 133 if (isIdentifiedObject(V)) 134 return V; 135 136 return 0; 137 } 138 139 void ScheduleDAGInstrs::startBlock(MachineBasicBlock *bb) { 140 BB = bb; 141 } 142 143 void ScheduleDAGInstrs::finishBlock() { 144 // Subclasses should no longer refer to the old block. 145 BB = 0; 146 } 147 148 /// Initialize the map with the number of registers. 149 void Reg2SUnitsMap::setRegLimit(unsigned Limit) { 150 PhysRegSet.setUniverse(Limit); 151 SUnits.resize(Limit); 152 } 153 154 /// Clear the map without deallocating storage. 155 void Reg2SUnitsMap::clear() { 156 for (const_iterator I = reg_begin(), E = reg_end(); I != E; ++I) { 157 SUnits[*I].clear(); 158 } 159 PhysRegSet.clear(); 160 } 161 162 /// Initialize the DAG and common scheduler state for the current scheduling 163 /// region. This does not actually create the DAG, only clears it. The 164 /// scheduling driver may call BuildSchedGraph multiple times per scheduling 165 /// region. 166 void ScheduleDAGInstrs::enterRegion(MachineBasicBlock *bb, 167 MachineBasicBlock::iterator begin, 168 MachineBasicBlock::iterator end, 169 unsigned endcount) { 170 assert(bb == BB && "startBlock should set BB"); 171 RegionBegin = begin; 172 RegionEnd = end; 173 EndIndex = endcount; 174 MISUnitMap.clear(); 175 176 ScheduleDAG::clearDAG(); 177 } 178 179 /// Close the current scheduling region. Don't clear any state in case the 180 /// driver wants to refer to the previous scheduling region. 181 void ScheduleDAGInstrs::exitRegion() { 182 // Nothing to do. 183 } 184 185 /// addSchedBarrierDeps - Add dependencies from instructions in the current 186 /// list of instructions being scheduled to scheduling barrier by adding 187 /// the exit SU to the register defs and use list. This is because we want to 188 /// make sure instructions which define registers that are either used by 189 /// the terminator or are live-out are properly scheduled. This is 190 /// especially important when the definition latency of the return value(s) 191 /// are too high to be hidden by the branch or when the liveout registers 192 /// used by instructions in the fallthrough block. 193 void ScheduleDAGInstrs::addSchedBarrierDeps() { 194 MachineInstr *ExitMI = RegionEnd != BB->end() ? &*RegionEnd : 0; 195 ExitSU.setInstr(ExitMI); 196 bool AllDepKnown = ExitMI && 197 (ExitMI->isCall() || ExitMI->isBarrier()); 198 if (ExitMI && AllDepKnown) { 199 // If it's a call or a barrier, add dependencies on the defs and uses of 200 // instruction. 201 for (unsigned i = 0, e = ExitMI->getNumOperands(); i != e; ++i) { 202 const MachineOperand &MO = ExitMI->getOperand(i); 203 if (!MO.isReg() || MO.isDef()) continue; 204 unsigned Reg = MO.getReg(); 205 if (Reg == 0) continue; 206 207 if (TRI->isPhysicalRegister(Reg)) 208 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1)); 209 else { 210 assert(!IsPostRA && "Virtual register encountered after regalloc."); 211 addVRegUseDeps(&ExitSU, i); 212 } 213 } 214 } else { 215 // For others, e.g. fallthrough, conditional branch, assume the exit 216 // uses all the registers that are livein to the successor blocks. 217 assert(Uses.empty() && "Uses in set before adding deps?"); 218 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 219 SE = BB->succ_end(); SI != SE; ++SI) 220 for (MachineBasicBlock::livein_iterator I = (*SI)->livein_begin(), 221 E = (*SI)->livein_end(); I != E; ++I) { 222 unsigned Reg = *I; 223 if (!Uses.contains(Reg)) 224 Uses[Reg].push_back(PhysRegSUOper(&ExitSU, -1)); 225 } 226 } 227 } 228 229 /// MO is an operand of SU's instruction that defines a physical register. Add 230 /// data dependencies from SU to any uses of the physical register. 231 void ScheduleDAGInstrs::addPhysRegDataDeps(SUnit *SU, unsigned OperIdx) { 232 const MachineOperand &MO = SU->getInstr()->getOperand(OperIdx); 233 assert(MO.isDef() && "expect physreg def"); 234 235 // Ask the target if address-backscheduling is desirable, and if so how much. 236 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 237 238 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true); 239 Alias.isValid(); ++Alias) { 240 if (!Uses.contains(*Alias)) 241 continue; 242 std::vector<PhysRegSUOper> &UseList = Uses[*Alias]; 243 for (unsigned i = 0, e = UseList.size(); i != e; ++i) { 244 SUnit *UseSU = UseList[i].SU; 245 if (UseSU == SU) 246 continue; 247 248 SDep dep(SU, SDep::Data, 1, *Alias); 249 250 // Adjust the dependence latency using operand def/use information, 251 // then allow the target to perform its own adjustments. 252 int UseOp = UseList[i].OpIdx; 253 MachineInstr *RegUse = UseOp < 0 ? 0 : UseSU->getInstr(); 254 dep.setLatency( 255 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, 256 RegUse, UseOp, /*FindMin=*/false)); 257 dep.setMinLatency( 258 SchedModel.computeOperandLatency(SU->getInstr(), OperIdx, 259 RegUse, UseOp, /*FindMin=*/true)); 260 261 ST.adjustSchedDependency(SU, UseSU, dep); 262 UseSU->addPred(dep); 263 } 264 } 265 } 266 267 /// addPhysRegDeps - Add register dependencies (data, anti, and output) from 268 /// this SUnit to following instructions in the same scheduling region that 269 /// depend the physical register referenced at OperIdx. 270 void ScheduleDAGInstrs::addPhysRegDeps(SUnit *SU, unsigned OperIdx) { 271 const MachineInstr *MI = SU->getInstr(); 272 const MachineOperand &MO = MI->getOperand(OperIdx); 273 274 // Optionally add output and anti dependencies. For anti 275 // dependencies we use a latency of 0 because for a multi-issue 276 // target we want to allow the defining instruction to issue 277 // in the same cycle as the using instruction. 278 // TODO: Using a latency of 1 here for output dependencies assumes 279 // there's no cost for reusing registers. 280 SDep::Kind Kind = MO.isUse() ? SDep::Anti : SDep::Output; 281 for (MCRegAliasIterator Alias(MO.getReg(), TRI, true); 282 Alias.isValid(); ++Alias) { 283 if (!Defs.contains(*Alias)) 284 continue; 285 std::vector<PhysRegSUOper> &DefList = Defs[*Alias]; 286 for (unsigned i = 0, e = DefList.size(); i != e; ++i) { 287 SUnit *DefSU = DefList[i].SU; 288 if (DefSU == &ExitSU) 289 continue; 290 if (DefSU != SU && 291 (Kind != SDep::Output || !MO.isDead() || 292 !DefSU->getInstr()->registerDefIsDead(*Alias))) { 293 if (Kind == SDep::Anti) 294 DefSU->addPred(SDep(SU, Kind, 0, /*Reg=*/*Alias)); 295 else { 296 unsigned AOLat = 297 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()); 298 DefSU->addPred(SDep(SU, Kind, AOLat, /*Reg=*/*Alias)); 299 } 300 } 301 } 302 } 303 304 if (!MO.isDef()) { 305 // Either insert a new Reg2SUnits entry with an empty SUnits list, or 306 // retrieve the existing SUnits list for this register's uses. 307 // Push this SUnit on the use list. 308 Uses[MO.getReg()].push_back(PhysRegSUOper(SU, OperIdx)); 309 } 310 else { 311 addPhysRegDataDeps(SU, OperIdx); 312 313 // Either insert a new Reg2SUnits entry with an empty SUnits list, or 314 // retrieve the existing SUnits list for this register's defs. 315 std::vector<PhysRegSUOper> &DefList = Defs[MO.getReg()]; 316 317 // clear this register's use list 318 if (Uses.contains(MO.getReg())) 319 Uses[MO.getReg()].clear(); 320 321 if (!MO.isDead()) 322 DefList.clear(); 323 324 // Calls will not be reordered because of chain dependencies (see 325 // below). Since call operands are dead, calls may continue to be added 326 // to the DefList making dependence checking quadratic in the size of 327 // the block. Instead, we leave only one call at the back of the 328 // DefList. 329 if (SU->isCall) { 330 while (!DefList.empty() && DefList.back().SU->isCall) 331 DefList.pop_back(); 332 } 333 // Defs are pushed in the order they are visited and never reordered. 334 DefList.push_back(PhysRegSUOper(SU, OperIdx)); 335 } 336 } 337 338 /// addVRegDefDeps - Add register output and data dependencies from this SUnit 339 /// to instructions that occur later in the same scheduling region if they read 340 /// from or write to the virtual register defined at OperIdx. 341 /// 342 /// TODO: Hoist loop induction variable increments. This has to be 343 /// reevaluated. Generally, IV scheduling should be done before coalescing. 344 void ScheduleDAGInstrs::addVRegDefDeps(SUnit *SU, unsigned OperIdx) { 345 const MachineInstr *MI = SU->getInstr(); 346 unsigned Reg = MI->getOperand(OperIdx).getReg(); 347 348 // Singly defined vregs do not have output/anti dependencies. 349 // The current operand is a def, so we have at least one. 350 // Check here if there are any others... 351 if (MRI.hasOneDef(Reg)) 352 return; 353 354 // Add output dependence to the next nearest def of this vreg. 355 // 356 // Unless this definition is dead, the output dependence should be 357 // transitively redundant with antidependencies from this definition's 358 // uses. We're conservative for now until we have a way to guarantee the uses 359 // are not eliminated sometime during scheduling. The output dependence edge 360 // is also useful if output latency exceeds def-use latency. 361 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg); 362 if (DefI == VRegDefs.end()) 363 VRegDefs.insert(VReg2SUnit(Reg, SU)); 364 else { 365 SUnit *DefSU = DefI->SU; 366 if (DefSU != SU && DefSU != &ExitSU) { 367 unsigned OutLatency = 368 SchedModel.computeOutputLatency(MI, OperIdx, DefSU->getInstr()); 369 DefSU->addPred(SDep(SU, SDep::Output, OutLatency, Reg)); 370 } 371 DefI->SU = SU; 372 } 373 } 374 375 /// addVRegUseDeps - Add a register data dependency if the instruction that 376 /// defines the virtual register used at OperIdx is mapped to an SUnit. Add a 377 /// register antidependency from this SUnit to instructions that occur later in 378 /// the same scheduling region if they write the virtual register. 379 /// 380 /// TODO: Handle ExitSU "uses" properly. 381 void ScheduleDAGInstrs::addVRegUseDeps(SUnit *SU, unsigned OperIdx) { 382 MachineInstr *MI = SU->getInstr(); 383 unsigned Reg = MI->getOperand(OperIdx).getReg(); 384 385 // Lookup this operand's reaching definition. 386 assert(LIS && "vreg dependencies requires LiveIntervals"); 387 LiveRangeQuery LRQ(LIS->getInterval(Reg), LIS->getInstructionIndex(MI)); 388 VNInfo *VNI = LRQ.valueIn(); 389 390 // VNI will be valid because MachineOperand::readsReg() is checked by caller. 391 assert(VNI && "No value to read by operand"); 392 MachineInstr *Def = LIS->getInstructionFromIndex(VNI->def); 393 // Phis and other noninstructions (after coalescing) have a NULL Def. 394 if (Def) { 395 SUnit *DefSU = getSUnit(Def); 396 if (DefSU) { 397 // The reaching Def lives within this scheduling region. 398 // Create a data dependence. 399 SDep dep(DefSU, SDep::Data, 1, Reg); 400 // Adjust the dependence latency using operand def/use information, then 401 // allow the target to perform its own adjustments. 402 int DefOp = Def->findRegisterDefOperandIdx(Reg); 403 dep.setLatency( 404 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, false)); 405 dep.setMinLatency( 406 SchedModel.computeOperandLatency(Def, DefOp, MI, OperIdx, true)); 407 408 const TargetSubtargetInfo &ST = TM.getSubtarget<TargetSubtargetInfo>(); 409 ST.adjustSchedDependency(DefSU, SU, const_cast<SDep &>(dep)); 410 SU->addPred(dep); 411 } 412 } 413 414 // Add antidependence to the following def of the vreg it uses. 415 VReg2SUnitMap::iterator DefI = VRegDefs.find(Reg); 416 if (DefI != VRegDefs.end() && DefI->SU != SU) 417 DefI->SU->addPred(SDep(SU, SDep::Anti, 0, Reg)); 418 } 419 420 /// Return true if MI is an instruction we are unable to reason about 421 /// (like a call or something with unmodeled side effects). 422 static inline bool isGlobalMemoryObject(AliasAnalysis *AA, MachineInstr *MI) { 423 if (MI->isInlineAsm()) { 424 // Until we can tell if an inline assembly instruction accesses 425 // memory, we must assume all such instructions do so. 426 return true; 427 } 428 if (MI->isCall() || MI->hasUnmodeledSideEffects() || 429 (MI->hasOrderedMemoryRef() && 430 (!MI->mayLoad() || !MI->isInvariantLoad(AA)))) 431 return true; 432 return false; 433 } 434 435 // This MI might have either incomplete info, or known to be unsafe 436 // to deal with (i.e. volatile object). 437 static inline bool isUnsafeMemoryObject(MachineInstr *MI, 438 const MachineFrameInfo *MFI) { 439 if (!MI || MI->memoperands_empty()) 440 return true; 441 // We purposefully do no check for hasOneMemOperand() here 442 // in hope to trigger an assert downstream in order to 443 // finish implementation. 444 if ((*MI->memoperands_begin())->isVolatile() || 445 MI->hasUnmodeledSideEffects()) 446 return true; 447 448 const Value *V = (*MI->memoperands_begin())->getValue(); 449 if (!V) 450 return true; 451 452 V = getUnderlyingObject(V); 453 if (const PseudoSourceValue *PSV = dyn_cast<PseudoSourceValue>(V)) { 454 // Similarly to getUnderlyingObjectForInstr: 455 // For now, ignore PseudoSourceValues which may alias LLVM IR values 456 // because the code that uses this function has no way to cope with 457 // such aliases. 458 if (PSV->isAliased(MFI)) 459 return true; 460 } 461 // Does this pointer refer to a distinct and identifiable object? 462 if (!isIdentifiedObject(V)) 463 return true; 464 465 return false; 466 } 467 468 /// This returns true if the two MIs need a chain edge betwee them. 469 /// If these are not even memory operations, we still may need 470 /// chain deps between them. The question really is - could 471 /// these two MIs be reordered during scheduling from memory dependency 472 /// point of view. 473 static bool MIsNeedChainEdge(AliasAnalysis *AA, const MachineFrameInfo *MFI, 474 MachineInstr *MIa, 475 MachineInstr *MIb) { 476 // Cover a trivial case - no edge is need to itself. 477 if (MIa == MIb) 478 return false; 479 480 if (isUnsafeMemoryObject(MIa, MFI) || isUnsafeMemoryObject(MIb, MFI)) 481 return true; 482 483 // If we are dealing with two "normal" loads, we do not need an edge 484 // between them - they could be reordered. 485 if (!MIa->mayStore() && !MIb->mayStore()) 486 return false; 487 488 // To this point analysis is generic. From here on we do need AA. 489 if (!AA) 490 return true; 491 492 MachineMemOperand *MMOa = *MIa->memoperands_begin(); 493 MachineMemOperand *MMOb = *MIb->memoperands_begin(); 494 495 // FIXME: Need to handle multiple memory operands to support all targets. 496 if (!MIa->hasOneMemOperand() || !MIb->hasOneMemOperand()) 497 llvm_unreachable("Multiple memory operands."); 498 499 // The following interface to AA is fashioned after DAGCombiner::isAlias 500 // and operates with MachineMemOperand offset with some important 501 // assumptions: 502 // - LLVM fundamentally assumes flat address spaces. 503 // - MachineOperand offset can *only* result from legalization and 504 // cannot affect queries other than the trivial case of overlap 505 // checking. 506 // - These offsets never wrap and never step outside 507 // of allocated objects. 508 // - There should never be any negative offsets here. 509 // 510 // FIXME: Modify API to hide this math from "user" 511 // FIXME: Even before we go to AA we can reason locally about some 512 // memory objects. It can save compile time, and possibly catch some 513 // corner cases not currently covered. 514 515 assert ((MMOa->getOffset() >= 0) && "Negative MachineMemOperand offset"); 516 assert ((MMOb->getOffset() >= 0) && "Negative MachineMemOperand offset"); 517 518 int64_t MinOffset = std::min(MMOa->getOffset(), MMOb->getOffset()); 519 int64_t Overlapa = MMOa->getSize() + MMOa->getOffset() - MinOffset; 520 int64_t Overlapb = MMOb->getSize() + MMOb->getOffset() - MinOffset; 521 522 AliasAnalysis::AliasResult AAResult = AA->alias( 523 AliasAnalysis::Location(MMOa->getValue(), Overlapa, 524 MMOa->getTBAAInfo()), 525 AliasAnalysis::Location(MMOb->getValue(), Overlapb, 526 MMOb->getTBAAInfo())); 527 528 return (AAResult != AliasAnalysis::NoAlias); 529 } 530 531 /// This recursive function iterates over chain deps of SUb looking for 532 /// "latest" node that needs a chain edge to SUa. 533 static unsigned 534 iterateChainSucc(AliasAnalysis *AA, const MachineFrameInfo *MFI, 535 SUnit *SUa, SUnit *SUb, SUnit *ExitSU, unsigned *Depth, 536 SmallPtrSet<const SUnit*, 16> &Visited) { 537 if (!SUa || !SUb || SUb == ExitSU) 538 return *Depth; 539 540 // Remember visited nodes. 541 if (!Visited.insert(SUb)) 542 return *Depth; 543 // If there is _some_ dependency already in place, do not 544 // descend any further. 545 // TODO: Need to make sure that if that dependency got eliminated or ignored 546 // for any reason in the future, we would not violate DAG topology. 547 // Currently it does not happen, but makes an implicit assumption about 548 // future implementation. 549 // 550 // Independently, if we encounter node that is some sort of global 551 // object (like a call) we already have full set of dependencies to it 552 // and we can stop descending. 553 if (SUa->isSucc(SUb) || 554 isGlobalMemoryObject(AA, SUb->getInstr())) 555 return *Depth; 556 557 // If we do need an edge, or we have exceeded depth budget, 558 // add that edge to the predecessors chain of SUb, 559 // and stop descending. 560 if (*Depth > 200 || 561 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) { 562 SUb->addPred(SDep(SUa, SDep::Order, /*Latency=*/0, /*Reg=*/0, 563 /*isNormalMemory=*/true)); 564 return *Depth; 565 } 566 // Track current depth. 567 (*Depth)++; 568 // Iterate over chain dependencies only. 569 for (SUnit::const_succ_iterator I = SUb->Succs.begin(), E = SUb->Succs.end(); 570 I != E; ++I) 571 if (I->isCtrl()) 572 iterateChainSucc (AA, MFI, SUa, I->getSUnit(), ExitSU, Depth, Visited); 573 return *Depth; 574 } 575 576 /// This function assumes that "downward" from SU there exist 577 /// tail/leaf of already constructed DAG. It iterates downward and 578 /// checks whether SU can be aliasing any node dominated 579 /// by it. 580 static void adjustChainDeps(AliasAnalysis *AA, const MachineFrameInfo *MFI, 581 SUnit *SU, SUnit *ExitSU, std::set<SUnit *> &CheckList, 582 unsigned LatencyToLoad) { 583 if (!SU) 584 return; 585 586 SmallPtrSet<const SUnit*, 16> Visited; 587 unsigned Depth = 0; 588 589 for (std::set<SUnit *>::iterator I = CheckList.begin(), IE = CheckList.end(); 590 I != IE; ++I) { 591 if (SU == *I) 592 continue; 593 if (MIsNeedChainEdge(AA, MFI, SU->getInstr(), (*I)->getInstr())) { 594 unsigned Latency = ((*I)->getInstr()->mayLoad()) ? LatencyToLoad : 0; 595 (*I)->addPred(SDep(SU, SDep::Order, Latency, /*Reg=*/0, 596 /*isNormalMemory=*/true)); 597 } 598 // Now go through all the chain successors and iterate from them. 599 // Keep track of visited nodes. 600 for (SUnit::const_succ_iterator J = (*I)->Succs.begin(), 601 JE = (*I)->Succs.end(); J != JE; ++J) 602 if (J->isCtrl()) 603 iterateChainSucc (AA, MFI, SU, J->getSUnit(), 604 ExitSU, &Depth, Visited); 605 } 606 } 607 608 /// Check whether two objects need a chain edge, if so, add it 609 /// otherwise remember the rejected SU. 610 static inline 611 void addChainDependency (AliasAnalysis *AA, const MachineFrameInfo *MFI, 612 SUnit *SUa, SUnit *SUb, 613 std::set<SUnit *> &RejectList, 614 unsigned TrueMemOrderLatency = 0, 615 bool isNormalMemory = false) { 616 // If this is a false dependency, 617 // do not add the edge, but rememeber the rejected node. 618 if (!EnableAASchedMI || 619 MIsNeedChainEdge(AA, MFI, SUa->getInstr(), SUb->getInstr())) 620 SUb->addPred(SDep(SUa, SDep::Order, TrueMemOrderLatency, /*Reg=*/0, 621 isNormalMemory)); 622 else { 623 // Duplicate entries should be ignored. 624 RejectList.insert(SUb); 625 DEBUG(dbgs() << "\tReject chain dep between SU(" 626 << SUa->NodeNum << ") and SU(" 627 << SUb->NodeNum << ")\n"); 628 } 629 } 630 631 /// Create an SUnit for each real instruction, numbered in top-down toplological 632 /// order. The instruction order A < B, implies that no edge exists from B to A. 633 /// 634 /// Map each real instruction to its SUnit. 635 /// 636 /// After initSUnits, the SUnits vector cannot be resized and the scheduler may 637 /// hang onto SUnit pointers. We may relax this in the future by using SUnit IDs 638 /// instead of pointers. 639 /// 640 /// MachineScheduler relies on initSUnits numbering the nodes by their order in 641 /// the original instruction list. 642 void ScheduleDAGInstrs::initSUnits() { 643 // We'll be allocating one SUnit for each real instruction in the region, 644 // which is contained within a basic block. 645 SUnits.reserve(BB->size()); 646 647 for (MachineBasicBlock::iterator I = RegionBegin; I != RegionEnd; ++I) { 648 MachineInstr *MI = I; 649 if (MI->isDebugValue()) 650 continue; 651 652 SUnit *SU = newSUnit(MI); 653 MISUnitMap[MI] = SU; 654 655 SU->isCall = MI->isCall(); 656 SU->isCommutable = MI->isCommutable(); 657 658 // Assign the Latency field of SU using target-provided information. 659 SU->Latency = SchedModel.computeInstrLatency(SU->getInstr()); 660 } 661 } 662 663 /// If RegPressure is non null, compute register pressure as a side effect. The 664 /// DAG builder is an efficient place to do it because it already visits 665 /// operands. 666 void ScheduleDAGInstrs::buildSchedGraph(AliasAnalysis *AA, 667 RegPressureTracker *RPTracker) { 668 // Create an SUnit for each real instruction. 669 initSUnits(); 670 671 // We build scheduling units by walking a block's instruction list from bottom 672 // to top. 673 674 // Remember where a generic side-effecting instruction is as we procede. 675 SUnit *BarrierChain = 0, *AliasChain = 0; 676 677 // Memory references to specific known memory locations are tracked 678 // so that they can be given more precise dependencies. We track 679 // separately the known memory locations that may alias and those 680 // that are known not to alias 681 std::map<const Value *, SUnit *> AliasMemDefs, NonAliasMemDefs; 682 std::map<const Value *, std::vector<SUnit *> > AliasMemUses, NonAliasMemUses; 683 std::set<SUnit*> RejectMemNodes; 684 685 // Remove any stale debug info; sometimes BuildSchedGraph is called again 686 // without emitting the info from the previous call. 687 DbgValues.clear(); 688 FirstDbgValue = NULL; 689 690 assert(Defs.empty() && Uses.empty() && 691 "Only BuildGraph should update Defs/Uses"); 692 Defs.setRegLimit(TRI->getNumRegs()); 693 Uses.setRegLimit(TRI->getNumRegs()); 694 695 assert(VRegDefs.empty() && "Only BuildSchedGraph may access VRegDefs"); 696 // FIXME: Allow SparseSet to reserve space for the creation of virtual 697 // registers during scheduling. Don't artificially inflate the Universe 698 // because we want to assert that vregs are not created during DAG building. 699 VRegDefs.setUniverse(MRI.getNumVirtRegs()); 700 701 // Model data dependencies between instructions being scheduled and the 702 // ExitSU. 703 addSchedBarrierDeps(); 704 705 // Walk the list of instructions, from bottom moving up. 706 MachineInstr *PrevMI = NULL; 707 for (MachineBasicBlock::iterator MII = RegionEnd, MIE = RegionBegin; 708 MII != MIE; --MII) { 709 MachineInstr *MI = prior(MII); 710 if (MI && PrevMI) { 711 DbgValues.push_back(std::make_pair(PrevMI, MI)); 712 PrevMI = NULL; 713 } 714 715 if (MI->isDebugValue()) { 716 PrevMI = MI; 717 continue; 718 } 719 if (RPTracker) { 720 RPTracker->recede(); 721 assert(RPTracker->getPos() == prior(MII) && "RPTracker can't find MI"); 722 } 723 724 assert((!MI->isTerminator() || CanHandleTerminators) && !MI->isLabel() && 725 "Cannot schedule terminators or labels!"); 726 727 SUnit *SU = MISUnitMap[MI]; 728 assert(SU && "No SUnit mapped to this MI"); 729 730 // Add register-based dependencies (data, anti, and output). 731 for (unsigned j = 0, n = MI->getNumOperands(); j != n; ++j) { 732 const MachineOperand &MO = MI->getOperand(j); 733 if (!MO.isReg()) continue; 734 unsigned Reg = MO.getReg(); 735 if (Reg == 0) continue; 736 737 if (TRI->isPhysicalRegister(Reg)) 738 addPhysRegDeps(SU, j); 739 else { 740 assert(!IsPostRA && "Virtual register encountered!"); 741 if (MO.isDef()) 742 addVRegDefDeps(SU, j); 743 else if (MO.readsReg()) // ignore undef operands 744 addVRegUseDeps(SU, j); 745 } 746 } 747 748 // Add chain dependencies. 749 // Chain dependencies used to enforce memory order should have 750 // latency of 0 (except for true dependency of Store followed by 751 // aliased Load... we estimate that with a single cycle of latency 752 // assuming the hardware will bypass) 753 // Note that isStoreToStackSlot and isLoadFromStackSLot are not usable 754 // after stack slots are lowered to actual addresses. 755 // TODO: Use an AliasAnalysis and do real alias-analysis queries, and 756 // produce more precise dependence information. 757 unsigned TrueMemOrderLatency = MI->mayStore() ? 1 : 0; 758 if (isGlobalMemoryObject(AA, MI)) { 759 // Be conservative with these and add dependencies on all memory 760 // references, even those that are known to not alias. 761 for (std::map<const Value *, SUnit *>::iterator I = 762 NonAliasMemDefs.begin(), E = NonAliasMemDefs.end(); I != E; ++I) { 763 I->second->addPred(SDep(SU, SDep::Order, /*Latency=*/0)); 764 } 765 for (std::map<const Value *, std::vector<SUnit *> >::iterator I = 766 NonAliasMemUses.begin(), E = NonAliasMemUses.end(); I != E; ++I) { 767 for (unsigned i = 0, e = I->second.size(); i != e; ++i) 768 I->second[i]->addPred(SDep(SU, SDep::Order, TrueMemOrderLatency)); 769 } 770 // Add SU to the barrier chain. 771 if (BarrierChain) 772 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0)); 773 BarrierChain = SU; 774 // This is a barrier event that acts as a pivotal node in the DAG, 775 // so it is safe to clear list of exposed nodes. 776 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, 777 TrueMemOrderLatency); 778 RejectMemNodes.clear(); 779 NonAliasMemDefs.clear(); 780 NonAliasMemUses.clear(); 781 782 // fall-through 783 new_alias_chain: 784 // Chain all possibly aliasing memory references though SU. 785 if (AliasChain) { 786 unsigned ChainLatency = 0; 787 if (AliasChain->getInstr()->mayLoad()) 788 ChainLatency = TrueMemOrderLatency; 789 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes, 790 ChainLatency); 791 } 792 AliasChain = SU; 793 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k) 794 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes, 795 TrueMemOrderLatency); 796 for (std::map<const Value *, SUnit *>::iterator I = AliasMemDefs.begin(), 797 E = AliasMemDefs.end(); I != E; ++I) 798 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes); 799 for (std::map<const Value *, std::vector<SUnit *> >::iterator I = 800 AliasMemUses.begin(), E = AliasMemUses.end(); I != E; ++I) { 801 for (unsigned i = 0, e = I->second.size(); i != e; ++i) 802 addChainDependency(AA, MFI, SU, I->second[i], RejectMemNodes, 803 TrueMemOrderLatency); 804 } 805 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, 806 TrueMemOrderLatency); 807 PendingLoads.clear(); 808 AliasMemDefs.clear(); 809 AliasMemUses.clear(); 810 } else if (MI->mayStore()) { 811 bool MayAlias = true; 812 if (const Value *V = getUnderlyingObjectForInstr(MI, MFI, MayAlias)) { 813 // A store to a specific PseudoSourceValue. Add precise dependencies. 814 // Record the def in MemDefs, first adding a dep if there is 815 // an existing def. 816 std::map<const Value *, SUnit *>::iterator I = 817 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V)); 818 std::map<const Value *, SUnit *>::iterator IE = 819 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end()); 820 if (I != IE) { 821 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 822 0, true); 823 I->second = SU; 824 } else { 825 if (MayAlias) 826 AliasMemDefs[V] = SU; 827 else 828 NonAliasMemDefs[V] = SU; 829 } 830 // Handle the uses in MemUses, if there are any. 831 std::map<const Value *, std::vector<SUnit *> >::iterator J = 832 ((MayAlias) ? AliasMemUses.find(V) : NonAliasMemUses.find(V)); 833 std::map<const Value *, std::vector<SUnit *> >::iterator JE = 834 ((MayAlias) ? AliasMemUses.end() : NonAliasMemUses.end()); 835 if (J != JE) { 836 for (unsigned i = 0, e = J->second.size(); i != e; ++i) 837 addChainDependency(AA, MFI, SU, J->second[i], RejectMemNodes, 838 TrueMemOrderLatency, true); 839 J->second.clear(); 840 } 841 if (MayAlias) { 842 // Add dependencies from all the PendingLoads, i.e. loads 843 // with no underlying object. 844 for (unsigned k = 0, m = PendingLoads.size(); k != m; ++k) 845 addChainDependency(AA, MFI, SU, PendingLoads[k], RejectMemNodes, 846 TrueMemOrderLatency); 847 // Add dependence on alias chain, if needed. 848 if (AliasChain) 849 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes); 850 // But we also should check dependent instructions for the 851 // SU in question. 852 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, 853 TrueMemOrderLatency); 854 } 855 // Add dependence on barrier chain, if needed. 856 // There is no point to check aliasing on barrier event. Even if 857 // SU and barrier _could_ be reordered, they should not. In addition, 858 // we have lost all RejectMemNodes below barrier. 859 if (BarrierChain) 860 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0)); 861 } else { 862 // Treat all other stores conservatively. 863 goto new_alias_chain; 864 } 865 866 if (!ExitSU.isPred(SU)) 867 // Push store's up a bit to avoid them getting in between cmp 868 // and branches. 869 ExitSU.addPred(SDep(SU, SDep::Order, 0, 870 /*Reg=*/0, /*isNormalMemory=*/false, 871 /*isMustAlias=*/false, 872 /*isArtificial=*/true)); 873 } else if (MI->mayLoad()) { 874 bool MayAlias = true; 875 if (MI->isInvariantLoad(AA)) { 876 // Invariant load, no chain dependencies needed! 877 } else { 878 if (const Value *V = 879 getUnderlyingObjectForInstr(MI, MFI, MayAlias)) { 880 // A load from a specific PseudoSourceValue. Add precise dependencies. 881 std::map<const Value *, SUnit *>::iterator I = 882 ((MayAlias) ? AliasMemDefs.find(V) : NonAliasMemDefs.find(V)); 883 std::map<const Value *, SUnit *>::iterator IE = 884 ((MayAlias) ? AliasMemDefs.end() : NonAliasMemDefs.end()); 885 if (I != IE) 886 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes, 0, true); 887 if (MayAlias) 888 AliasMemUses[V].push_back(SU); 889 else 890 NonAliasMemUses[V].push_back(SU); 891 } else { 892 // A load with no underlying object. Depend on all 893 // potentially aliasing stores. 894 for (std::map<const Value *, SUnit *>::iterator I = 895 AliasMemDefs.begin(), E = AliasMemDefs.end(); I != E; ++I) 896 addChainDependency(AA, MFI, SU, I->second, RejectMemNodes); 897 898 PendingLoads.push_back(SU); 899 MayAlias = true; 900 } 901 if (MayAlias) 902 adjustChainDeps(AA, MFI, SU, &ExitSU, RejectMemNodes, /*Latency=*/0); 903 // Add dependencies on alias and barrier chains, if needed. 904 if (MayAlias && AliasChain) 905 addChainDependency(AA, MFI, SU, AliasChain, RejectMemNodes); 906 if (BarrierChain) 907 BarrierChain->addPred(SDep(SU, SDep::Order, /*Latency=*/0)); 908 } 909 } 910 } 911 if (PrevMI) 912 FirstDbgValue = PrevMI; 913 914 Defs.clear(); 915 Uses.clear(); 916 VRegDefs.clear(); 917 PendingLoads.clear(); 918 } 919 920 void ScheduleDAGInstrs::dumpNode(const SUnit *SU) const { 921 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 922 SU->getInstr()->dump(); 923 #endif 924 } 925 926 std::string ScheduleDAGInstrs::getGraphNodeLabel(const SUnit *SU) const { 927 std::string s; 928 raw_string_ostream oss(s); 929 if (SU == &EntrySU) 930 oss << "<entry>"; 931 else if (SU == &ExitSU) 932 oss << "<exit>"; 933 else 934 SU->getInstr()->print(oss); 935 return oss.str(); 936 } 937 938 /// Return the basic block label. It is not necessarilly unique because a block 939 /// contains multiple scheduling regions. But it is fine for visualization. 940 std::string ScheduleDAGInstrs::getDAGName() const { 941 return "dag." + BB->getFullName(); 942 } 943 944 namespace { 945 /// \brief Manage the stack used by a reverse depth-first search over the DAG. 946 class SchedDAGReverseDFS { 947 std::vector<std::pair<const SUnit*, SUnit::const_pred_iterator> > DFSStack; 948 public: 949 bool isComplete() const { return DFSStack.empty(); } 950 951 void follow(const SUnit *SU) { 952 DFSStack.push_back(std::make_pair(SU, SU->Preds.begin())); 953 } 954 void advance() { ++DFSStack.back().second; } 955 956 void backtrack() { DFSStack.pop_back(); } 957 958 const SUnit *getCurr() const { return DFSStack.back().first; } 959 960 SUnit::const_pred_iterator getPred() const { return DFSStack.back().second; } 961 962 SUnit::const_pred_iterator getPredEnd() const { 963 return getCurr()->Preds.end(); 964 } 965 }; 966 } // anonymous 967 968 void ScheduleDAGILP::resize(unsigned NumSUnits) { 969 ILPValues.resize(NumSUnits); 970 } 971 972 ILPValue ScheduleDAGILP::getILP(const SUnit *SU) { 973 return ILPValues[SU->NodeNum]; 974 } 975 976 // A leaf node has an ILP of 1/1. 977 static ILPValue initILP(const SUnit *SU) { 978 unsigned Cnt = SU->getInstr()->isTransient() ? 0 : 1; 979 return ILPValue(Cnt, 1 + SU->getDepth()); 980 } 981 982 /// Compute an ILP metric for all nodes in the subDAG reachable via depth-first 983 /// search from this root. 984 void ScheduleDAGILP::computeILP(const SUnit *Root) { 985 if (!IsBottomUp) 986 llvm_unreachable("Top-down ILP metric is unimplemnted"); 987 988 SchedDAGReverseDFS DFS; 989 // Mark a node visited by validating it. 990 ILPValues[Root->NodeNum] = initILP(Root); 991 DFS.follow(Root); 992 for (;;) { 993 // Traverse the leftmost path as far as possible. 994 while (DFS.getPred() != DFS.getPredEnd()) { 995 const SUnit *PredSU = DFS.getPred()->getSUnit(); 996 DFS.advance(); 997 // If the pred is already valid, skip it. 998 if (ILPValues[PredSU->NodeNum].isValid()) 999 continue; 1000 ILPValues[PredSU->NodeNum] = initILP(PredSU); 1001 DFS.follow(PredSU); 1002 } 1003 // Visit the top of the stack in postorder and backtrack. 1004 unsigned PredCount = ILPValues[DFS.getCurr()->NodeNum].InstrCount; 1005 DFS.backtrack(); 1006 if (DFS.isComplete()) 1007 break; 1008 // Add the recently finished predecessor's bottom-up descendent count. 1009 ILPValues[DFS.getCurr()->NodeNum].InstrCount += PredCount; 1010 } 1011 } 1012 1013 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1014 void ILPValue::print(raw_ostream &OS) const { 1015 if (!isValid()) 1016 OS << "BADILP"; 1017 OS << InstrCount << " / " << Cycles << " = " 1018 << format("%g", ((double)InstrCount / Cycles)); 1019 } 1020 1021 void ILPValue::dump() const { 1022 dbgs() << *this << '\n'; 1023 } 1024 1025 namespace llvm { 1026 1027 raw_ostream &operator<<(raw_ostream &OS, const ILPValue &Val) { 1028 Val.print(OS); 1029 return OS; 1030 } 1031 1032 } // namespace llvm 1033 #endif // !NDEBUG || LLVM_ENABLE_DUMP 1034